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

查看:131
本文介绍了二进制文件已损坏-如何使用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
        }
    }); }} ]);

我的服务方法是这样:

@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天全站免登陆