我在用ASP.NET Web API.
我想从 API(API 生成的)使用 C# 下载 PDF。
我可以让 API 返回一个byte[]
?对于 C# 应用程序,我可以这样做:
byte[] pdf = client.DownloadData("urlToAPI");?
and
File.WriteAllBytes()?
最好返回其中包含 StreamContent 的 HttpResponseMessage。
这是示例:
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;
}
UPDATE来自评论者patridge:
如果其他人到达这里希望从字节数组而不是实际文件发送响应,您将需要使用new ByteArrayContent(someData)
代替StreamContent
(see here).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)