0

My goal is to create a zip file, add a text file to it, save it as stream and send it over to the client where it can download it.

But when I try to download it, I get an invalid zip file but it has at least more and less the correct size. My guess is that I'm doing something completly wrong with the stream on the client-side.

How can I send a zip file as stream to the client?

Controller that sends the zip file :

var zipFile = new ZipFile();
var stream = new MemoryStream();

zipFile.AddFile("path/to/file");
zipFile.Save(stream);
stream.Seek(0, SeekOrigin.Begin);

var httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StreamContent(stream);
httpResponseMessage.Content.Headers.Add("zip-filename", "test_originalfile.zip");
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "test_originalfile.zip";
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;

Controller that receives it:

$http.get(applicationServerUrl + '/api/UploadedFiles/GetZip?uploadedFileId=' + uploadedFileId)
.success(function (data, status, headers) {
    headers = headers();

    var filename = headers['zip-filename'];
    var contentType = headers['content-type'];

    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);
    }
}).error(function (data) {
    console.log(data);
});
SuffPanda
  • 348
  • 2
  • 17
  • I don't get the link between your problem and your question. Please see instructions to create a [Minimum, Complete, Verifiable Example](https://stackoverflow.com/help/mcve). – Tim Rogers Apr 04 '17 at 13:14
  • @TimRogers sorry for my unclear question. I edit it. I hope you understand this better. – SuffPanda Apr 04 '17 at 13:47
  • 1
    Why are you making life so hard for yourself on the client? What's wrong with `window.location.href = applicationServerUrl + '/api/UploadedFiles/GetZip?uploadedFileId=' + uploadedFileId`? – Tim Rogers Apr 04 '17 at 13:56
  • Nothing... just love to make my life harder than it is already thanks to copy n' paste stuff without thinking about what I'm copying... it solved my problem. – SuffPanda Apr 04 '17 at 14:11

0 Answers0