我有一个Web Api控制器方法,它获取传递的文档ID,它应该为这些请求的ID单独返回文档文件。我已尝试从以下链接中接受的答案来实现此功能,但它无法正常工作。我不知道我哪里出错了。
https://stackoverflow.com/questions/12266422/whats-the-best-way-to-serve-up-multiple-binary-files-from-a-single-webapi-metho
我的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 / multipart内容用于电子邮件消息(https://en.wikipedia.org/wiki/MIME#Multipart_messages),它从未打算在HTTP事务的客户端接收和解析。有些浏览器确实实现了它,有些浏览器却没有。
或者,您可以更改API以接受单个docId,并从客户端为每个docId迭代API。
我认为唯一的方法就是将所有文件压缩,然后下载一个zip文件。我想你可以使用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");
}
}