简体   繁体   中英

How to download a binary file returned from HTTP:POST request via angular.js?

I am working on an Angular.js based viewer for a server I've built, trying to add a "execute & download" button.

The way I'm sending the request to execute something is via HTTP:POST request, with headers :

"Accept" = "application/zip"
"X-MyApp-URI = "path/to/my/file/that/the/server/can/access/to"

The respons of the server to this kind of request is basically :

X-Powered-By: Servlet/3.0
Content-Type: application/zip
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Content-Disposition, Accept, Authorization, X-.....
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Origin: *
Content-Disposition: inline; filename="result.zip"
Transfer-Encoding: chunked
Date: Mon, 02 Nov 2015 15:29:42 GMT

I've tried this execution with both RESTClient 3.4 & Postman apps, and in both cases, the resulted file downloaded was the correct zip I've sent.

Here is the code I'm trying to execute via my web application :

var config = {'Accept':'application/zip', 'X-MyApp-URI' = 'path..'};
$http.post("../serverPath",{responseType: "bufferArray"}, config)
    .success(function (response) {
        var bytes = new Array(response.length);
        for (var i = 0; i < response.length; i++) {
            bytes[i] = response.charCodeAt(i)
        }
        var bytesUint = new Uint8Array(bytes);
        var blob = new Blob(bytesUint, {type: 'application/zip'});
        var blobUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.href = blobUrl;
        a.download = 'result.zip';
        a.click();
});

Unfortunately, I've tried almost every combination of parameters I was able to find in the web, and nothing helps, the files downloaded via the blob above are always corrupted.

Solution I can work with are around pure JS code, jQuery or specifically Angular.JS & any Apache already developed plugin that might assist solving this issue.

Try passing the Uint8Array directly to the Blob as follows:

var config = {'Accept':'application/zip', 'X-MyApp-URI' = 'path..'};
$http.post("../serverPath",{responseType: "bufferArray"}, config)
    .success(function (response) {
        var bytesUint = new Uint8Array(response);
        var blob = new Blob([bytesUint], {type: 'application/zip'});
        var blobUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.href = blobUrl;
        a.download = 'result.zip';
        a.click();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM