邮政编码无效。如何将zip文件作为流发送到客户端?

时间:2017-04-04 12:53:18

标签: c# angularjs asp.net-mvc dotnetzip

我的目标是创建一个zip文件,向其中添加一个文本文件,将其另存为流并将其发送到客户端,然后下载它。

但是当我尝试下载它时,我得到一个无效的zip文件,但它至少有正确的大小。我的猜测是,我正在做客户端流的完全错误。

如何将zip文件作为流发送到客户端?

发送zip文件的控制器:

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;

接收它的控制器:

$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);
});

0 个答案:

没有答案