不从路由c#接收数据
本文关键字:数据 路由 | 更新日期: 2023-09-27 18:15:48
我试图从服务器路由返回图像,但我得到一个是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;
在将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;