如何使用 Web API 返回文件? [英] How to return a file using Web API?
问题描述
我正在使用 ASP.NET Web API.
我想从 API(API 生成)下载带有 C# 的 PDF.
I am using ASP.NET Web API.
I want to download a PDF with C# from the API (that the API generates).
我可以让 API 返回一个 byte[]
吗?对于 C# 应用程序,我可以这样做:
Can I just have the API return a byte[]
? and for the C# application can I just do:
byte[] pdf = client.DownloadData("urlToAPI");?
和
File.WriteAllBytes()?
推荐答案
最好返回包含 StreamContent 的 HttpResponseMessage.
Better to return HttpResponseMessage with StreamContent inside of it.
示例如下:
public HttpResponseMessage GetFile(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string fileName;
string localFilePath;
int fileSize;
localFilePath = getFileFromID(id, out fileName, out fileSize);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
UPD 来自 patridge 的评论:如果其他人想要从字节数组而不是实际文件发送响应,您将需要使用 new ByteArrayContent(someData) 而不是 StreamContent(请参阅 此处).
UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).
这篇关于如何使用 Web API 返回文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!