What is wrong with my download of a zip file from

2019-09-18 10:15发布

问题:

I'm trying to do the following:

  1. The user fill a form and send it in .JSON to the server
  2. With the form, the server generate some .CSV files and put them all together in a .ZIP file.
  3. The server send the .ZIP file and the user download it.

After some research I have wrote this code:

My Controller:

[HttpPost]
        [Route("routeToMyAPI")]
        public HttpResponseMessage Process(Form form)
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(<streamToMyGeneratedZipFile>)
            };

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "fileName.zip"
            };

            return result;
        }

My Service:

angular.module('app')
  .factory('MyService', function ($http) {
    return {
      Process: function (form) {
        var req = $http.post('rest/example/process', form);
        return req;
      }
    };
  });

My Controller:

this.submit = function () {
    var Form = {};

    var formPost = MyService.Process(Form);
    formPost.then(function (data) {
      var a = document.createElement('a');
      var blob = new Blob([data], { 'type': "application/octet-stream" });
      a.href = URL.createObjectURL(blob);
      a.download = "fileName.zip";
      a.click();
    }, function (error) {
      alert('An error occured !');
    });
  };

I have parts 1 & 2 working, but I don't have find the way to call my ASP API to download the .ZIP file.

When I call the submit method of my Controller, I have a fileName.zip who is downloaded on my PC but when I try to open it Windows says to me that it's not a valid archive.

What did I do wrong ? I'm a rookie in angularjs and ASP so any help will be welcomed.

Thanks in advance.

回答1:

Several issues with your code:

After ZipArchive does its work, the position of the stream will be at the end. So you must reset it to the beginning like this before sending it:

zipStream.Position = 0;

Since you're setting the content type and file name of the file on the server already, just parse it on the client side.

var headers = data.headers(); //$http resolves to data, status, headers, config
var regex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var match = regex.exec(headers["content-disposition"]);
var fileName = match[1] || "myZipFile.zip";
fileName = fileName.replace(/\"/g, ""); //replace trailing and leading slashes

var contentType = headers["content-type"] || "application/octet-stream";

IE will not allow you to open blobs directly. You must use msSaveOrOpenBlob or msSaveBlob.

var blob = new Blob([data.data], { type: contentType });

  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    var a = document.createElement('a');
    var objectUrl = URL.createObjectURL(blob);
    a.href = URL.createObjectURL(blob);
    a.download = match[1];
    a.click();
  }

One last thing: the previous code won't work on firefox because firefox doesn't support clic(). Thanks to this thread this can be solved by adding this little snippet of code:

HTMLElement.prototype.click = function() {
   var evt = this.ownerDocument.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
   this.dispatchEvent(evt);
}