1

我有一个 Web Api 控制器方法,它获取传递的文档 ID,它应该为那些请求的 Id 单独返回文档文件。我已经尝试了以下链接中接受的答案来实现此功能,但它不起作用。我不知道我哪里做错了。

从单个 WebApi 方法提供多个二进制文件的最佳方法是什么?

我的 Web API 方法,

   public async Task<HttpResponseMessage> DownloadMultiDocumentAsync( 
             IClaimedUser user, string documentId)
    {
        List<long> docIds = documentId.Split(',').Select(long.Parse).ToList();
        List<Document> documentList = coreDataContext.Documents.Where(d => docIds.Contains(d.DocumentId) && d.IsActive).ToList();

        var content = new MultipartContent();
        CloudBlockBlob blob = null;

        var container = GetBlobClient(tenantInfo);
        var directory = container.GetDirectoryReference(
            string.Format(DirectoryNameConfigValue, tenantInfo.TenantId.ToString(), documentList[0].ProjectId));

        for (int docId = 0; docId < documentList.Count; docId++)
        {
            blob = directory.GetBlockBlobReference(DocumentNameConfigValue + documentList[docId].DocumentId);
            if (!blob.Exists()) continue;

            MemoryStream memStream = new MemoryStream();
            await blob.DownloadToStreamAsync(memStream);
            memStream.Seek(0, SeekOrigin.Begin);
            var streamContent = new StreamContent(memStream);
            content.Add(streamContent);

        }            
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        httpResponseMessage.Content = content;
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        httpResponseMessage.StatusCode = HttpStatusCode.OK;
        return httpResponseMessage;
    }

我尝试使用 2 个或更多文档 ID,但只下载了一个文件,而且格式也不正确(没有扩展名)。

4

2 回答 2

5

压缩是唯一可以在所有浏览器上获得一致结果的选项。MIME/multipart 内容用于电子邮件消息 ( https://en.wikipedia.org/wiki/MIME#Multipart_messages ),它从未打算在 HTTP 事务的客户端接收和解析。有些浏览器确实实现了它,有些则没有。

或者,您可以更改您的 API 以接收单个 docId,并从您的客户端为每个 docId 迭代您的 API。

于 2018-08-24T20:03:07.590 回答
2

我认为唯一的方法是压缩所有文件,然后下载一个压缩文件。我想您可以使用 dotnetzip 包,因为它易于使用。

一种方法是,您可以先将文件保存在磁盘上,然后流式传输 zip 进行下载。另一种方法是,您可以将它们压缩到内存中,然后在流中下载文件

public ActionResult Download()
{
    using (ZipFile zip = new ZipFile())
    {
        zip.AddDirectory(Server.MapPath("~/Directories/hello"));

        MemoryStream output = new MemoryStream();
        zip.Save(output);
        return File(output, "application/zip", "sample.zip");
    }  
}
于 2018-09-10T04:31:52.970 回答