【问题标题】:Zip Azure Storage Files and Return File from Web Api压缩 Azure 存储文件并从 Web Api 返回文件
【发布时间】:2019-12-11 21:39:06
【问题描述】:

我正在尝试使用 SharpZipLib 从存储在 Azure 存储上的文件创建一个 zip 文件。不幸的是,我无法返回它们,因为 Api 总是返回 Json:

{"Version":{"Major":1,"Minor":1,"Build":-1,"Revision":-1,"MajorRevision":-1,"MinorRevision":-1},"Content":{"Headers":[{"Key":"Content-Disposition","Value":["attachment; filename=Documents.zip"]},{"Key":"Content-Type","Value":["application/octet-stream"]},{"Key":"Content-Length","Value":["498"]}]},"StatusCode":200,"ReasonPhrase":"OK","Headers":[],"RequestMessage":null,"IsSuccessStatusCode":true}

我使用的压缩应该可以工作,但是我不确定一切是否正确,因为我永远无法看到该文件。

这是压缩文件并返回压缩文件的代码:

[HttpGet("DownloadFiles")]
public async Task<HttpResponseMessage> DownloadFiles(string invoiceNr, List<string> fileNames)
{
    List<CloudBlockBlob> blobs = _documentService.GetBlobs(invoiceNr, fileNames);

    MemoryStream outputMemStream = new MemoryStream();
    ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

    zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

    foreach (CloudBlockBlob blob in blobs)
    {
        using (MemoryStream blobStream = new MemoryStream())
        {
            await blob.DownloadToStreamAsync(blobStream);

            ZipEntry newEntry = new ZipEntry(blob.Name);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            StreamUtils.Copy(blobStream, zipStream, new byte[4096]);
            zipStream.CloseEntry();
        }
    }

    zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
    zipStream.Close();                  // Must finish the ZipOutputStream before using outputMemStream.

    outputMemStream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(outputMemStream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "Documents.zip";
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = outputMemStream.Length;
    return result;
}

从 WebAPi 返回文件的方式是否错误?我做错了什么吗?

提前感谢您的帮助。

【问题讨论】:

    标签: asp.net api asp.net-web-api zip sharpziplib


    【解决方案1】:

    当你声明你的 web 方法为

    public async Task<HttpResponseMessage> DownloadFiles(...)
    

    ASP.NET Core 将 HttpResponseMessage 视为模型,并且您的方法返回此文件序列化为 JSON 的实例。 这个方法的正确版本是

    public async Task<IActionResult> DownloadFiles()
    {
        ...
        return File(outputMemStream, "application/octet-stream", "Documents.zip");
    }
    

    【讨论】:

    • 谢谢,完成了!
    猜你喜欢
    • 2022-11-12
    • 2021-11-19
    • 1970-01-01
    • 2015-12-16
    • 2015-05-04
    • 2022-01-18
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多