Java 使用$http或jquery.ajax下载二进制文件时遇到问题

Java 使用$http或jquery.ajax下载二进制文件时遇到问题,java,angularjs,spring,zipfile,Java,Angularjs,Spring,Zipfile,我的问题是,我在客户端得到了错误大小的文件。这是我的@Controller @RequestMapping(value = "/download/{id}", method = RequestMethod.GET) public ResponseEntity<?> download(final HttpServletRequest request, final HttpServletResponse response

我的问题是,我在客户端得到了错误大小的文件。这是我的@Controller

@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<?> download(final HttpServletRequest request,
                                  final HttpServletResponse response,
                                  @PathVariable("id") final int id) throws IOException {
    try {
        // Pseudo-code for retrieving file from ID.
        Path zippath = getZipFile(id);

        if (!Files.exists(zippath)) {
            throw new IOException("File not found.");
        }

        ResponseEntity<InputStreamResource> result;
        return ResponseEntity.ok()
                             .contentLength(Files.size(zippath))
                             .contentType(MediaType.APPLICATION_OCTET_STREAM)
                             .body(new InputStreamResource(new FileInputStream(zippath.toFile())));
    } catch (Exception ex) {
        // ErrorInfo is another class, unimportant
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorInfo(ex));
    }
}

所以问题出在angular的$http服务上。我还尝试了jQuery的ajax方法。两者的结果相同。如果改用本机XMLHttpRequest,它将正常工作。因此Java代码是合理的。我首先验证了这一点,将文件直接暴露在互联网上,然后使用curl和直接访问浏览器,我设法下载了正确大小的文件。然后我找到了这个解决方案,这样我也可以通过javascript下载文件

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.withCredentials = true;
xhr.onreadystatechange = function (){
    if (xhr.readyState === 4) {
        var blob = xhr.response;
        FileSaver.saveAs(blob, filename);
    }
};
xhr.send();

为什么angular或jQuery给出错误的结果?我仍然不知道,但如果有人希望给出一个使用这些答案的答案,我们将不胜感激

我刚刚偶然发现$http请求中的'responseType',您可能正在寻找'blob':$http#用法

responseType:blob 对zip文件执行此操作

角度2+

this.http.get('http://localhost:8080/export', { responseType: ResponseContentType.Blob })
  .subscribe((res: any) => {
        const blob = new Blob([res._body], { type: 'application/zip' });
         saveAs(blob, "fileName.zip");

zippath.toFile()
中会发生什么?将路径对象转换为文件对象,以便我可以在FileInputStream中使用它。同样的事情。不知道为什么jquery/angular会增加文件大小并破坏数据。
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.withCredentials = true;
xhr.onreadystatechange = function (){
    if (xhr.readyState === 4) {
        var blob = xhr.response;
        FileSaver.saveAs(blob, filename);
    }
};
xhr.send();
this.http.get('http://localhost:8080/export', { responseType: ResponseContentType.Blob })
  .subscribe((res: any) => {
        const blob = new Blob([res._body], { type: 'application/zip' });
         saveAs(blob, "fileName.zip");