c# - 网络API : Download Multiple Files Separately

标签 c# azure web-applications asp.net-web-api2 httpresponsemessage

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

What's the best way to serve up multiple binary files from a single WebApi method?

我的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,但只下载了一个文件,而且该文件的格式也不正确(无扩展名)。

最佳答案

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

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

关于c# - 网络API : Download Multiple Files Separately,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010096/

相关文章:

c# - MVC3 应用程序中的通用 "back"按钮

c# - 移动要托管的 XML 文件

azure - ASP.NET MVC Core Azure Blob 图像调整器

java - 阻止用户向页面发出 GET 请求

java - Web应用程序和应用程序之间的区别?

ASP.NET Web 应用程序找不到程序集

c# - 同一时刻调用两次的方法

c# - 如何以编程方式为 Amazon S3 设置 Http Header?

c# - 池存在后更新 Azure Batch 自动缩放公式

python - Django channel 和 azure