我试图从服务器路由返回一张图像,但我得到的是 0 字节的图像。我怀疑这与我使用 MemoryStream
的方式有关。这是我的代码:
[HttpGet]
[Route("edit")]
public async Task<HttpResponseMessage> Edit(int pdfFileId)
{
var pdf = await PdfFileModel.PdfDbOps.QueryAsync((p => p.Id == pdfFileId));
IEnumerable<Image> pdfPagesAsImages = PdfOperations.PdfToImages(pdf.Data, 500);
MemoryStream imageMemoryStream = new MemoryStream();
pdfPagesAsImages.First().Save(imageMemoryStream, ImageFormat.Png);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(imageMemoryStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = pdf.Filename,
DispositionType = "attachment"
};
return response;
}
通过调试,我已验证 PdfToImages
方法正在运行,并且 imageMemoryStream
已填充来自该行的数据
pdfPagesAsImages.First().Save(imageMemoryStream, ImageFormat.Png);
但是在运行它时,我收到了一个正确命名但为 0 字节的附件。我需要更改什么才能接收整个文件?我认为这很简单,但我不确定是什么。提前致谢。
最佳答案
写入MemoryStream
后,Flush
然后将Position
设置为0:
imageMemoryStream.Flush();
imageMemoryStream.Position = 0;
关于c# - 未从路由 C# 接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910651/