二进制文件损坏 - 如何使用 AngularJS 下载二进制文件 [英] Binary files corrupted - How to Download Binary Files with AngularJS

查看:72
本文介绍了二进制文件损坏 - 如何使用 AngularJS 下载二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在客户端使用 angular 下载文件,此文件可以是任何格式,可以是 pdf 或 excel 或图像或 txt ...我的方法仅适用于 txt 文件,并为我提供了 excel 和图像的失败格式,而对于 pdf,它提供了一个空的 pdf.

I need to download a file using angular in client side, this file can have any format it could be a pdf or excel or image or txt ... my method works just for txt files and gives me a fail format for excel and image and for the pdf it gives an empty pdf.

所以在我的控制器中,这里是调用服务方法的函数:

so in my controller here is the function that calles the service method:

    vm.downloadFile = downloadFile;

    function downloadFile(file){
        var urlDir = "C://STCI//"+idpeticion;
        return VerDocServices.downloadFile(file,urlDir)
          .then(function(response) {
            var data = response.data;
            var filename = file;
            var contentType = 'application/octet-stream';//octet-stream             
            var linkElement = document.createElement('a');
            try {
                var blob = new Blob([ data ], {
                    type : contentType
                });
                var url = window.URL.createObjectURL(blob);
                linkElement.setAttribute('href', url);
                linkElement.setAttribute("download", filename);
                var clickEvent = new MouseEvent("click", {
                    "view" : window,
                    "bubbles" : true,
                    "cancelable" : false
                });
                linkElement.dispatchEvent(clickEvent);
            } catch (ex) {
                console.log(ex);
                throw ex;
            }
        }).catch(function(response) {
            alert('Se ha producido un error al exportar del documento');
            console.log(response.status);
            throw response;
        });
    }

我的 service.js 有:

and my service.js has:

angular.module('mecenzApp').service('VerDocServices',['$http',function($http) {

this.downloadFile = function(file,urlDir) {

    return $http.get('api/downloadFile', {
        params : {
            file : file,
            urlDir : urlDir
        }
    }); }} ]);

我的服务方法是这样的:

And my service method is this:

@GetMapping("/downloadFile")
@Timed
public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "file") String file, @RequestParam(value = "urlDir") String urlDir) {
    log.debug("GET ---------------- DOWNLOAD FILE : {}", file);
    log.debug("GET ---------------- From the DIRECTORY: {}",urlDir);

    InputStream fileStream;
    String filepath = urlDir+File.separator+file;
    try {
        File f = new File(filepath);
        log.debug("GET ---------------- FILE: {}",f.getPath());
        fileStream = new FileInputStream(f);
        byte[] contents = IOUtils.toByteArray(fileStream);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/octet-stream"));   
        String filename = file;
        headers.setContentDispositionFormData(filename, filename);
        ResponseEntity<byte[]> response2 = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
        fileStream.close();
        return response2;            
        
    } catch (FileNotFoundException e) {
       System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    }
   return null;
}

你能看一下并告诉我我错过了什么吗?

could you plz take a look and tell me what did I have missed??

谢谢你:)

推荐答案

如何使用 AngularJS 下载二进制文件

下载二进制文件时,设置responseType很重要:

app.service('VerDocServices',['$http',function($http) {

    this.downloadFile = function(url, file, urlDir) {
        var config = {
            //SET responseType
            responseType: 'blob',
            params : {
                file : file,
                urlDir : urlDir
            }
         };

        return $http.get(url, config)
          .then(function(response) {
            return response.data;
        }).catch(function(response) {
            console.log("ERROR: ", response.status);
            throw response;
        }); 
    }; 
}]);

如果省略 responseType,XHR API 默认转换为 UTF-8 将文本编码为 DOMString (UTF-16) 这会损坏 PDF、图像和其他二进制文件.

If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.

有关更多信息,请参阅 MDN Web API 参考 - XHR ResponseType

For more information, see MDN Web API Reference - XHR ResponseType

这篇关于二进制文件损坏 - 如何使用 AngularJS 下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆