我正在尝试从服务器路由返回一个图像,但我得到一个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字节的附件。为了接收整个文件,我需要更改什么?我认为这很简单,但我不确定是什么。提前谢谢。
答案 0 :(得分:2)
写入MemoryStream
,Flush
后,将Position
设为0:
imageMemoryStream.Flush();
imageMemoryStream.Position = 0;
答案 1 :(得分:0)
在将MemoryStream
传递给响应之前,您应将其重新开始。但你最好使用PushStreamContent
:
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new PushStreamContent(async (stream, content, context) =>
{
var pdf = await PdfFileModel.PdfDbOps.QueryAsync(p => p.Id == pdfFileId);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = pdf.Filename,
DispositionType = "attachment"
};
PdfOperations.PdfToImages(pdf.Data, 500).First().Save(stream, ImageFormat.Png);
}, "image/png");
return response;