Not Receiving Data from Route C#
Asked Answered
B

2

6

I'm attempting to return an image from a server route, but I'm getting one that is 0 bytes. I suspect it has something to do with how I'm using the MemoryStream. Here's my code:

[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;
}

Through debugging I have verified that the PdfToImages method is working and that imageMemoryStream gets filled with data from the line

pdfPagesAsImages.First().Save(imageMemoryStream, ImageFormat.Png);

However in running it, I receive an attachment that is properly named but is 0 bytes. What do I need to change in order to receive the whole file? I think it's something simple but I'm not sure what. Thanks in advance.

Bloodshed answered 2/10, 2015 at 15:28 Comment(1)
Maybe you have to set stream position to 0? imageMemoryStream.Position = 0;Claybourne
C
2

After writing to the MemoryStream, Flush it then set Position to 0:

imageMemoryStream.Flush();
imageMemoryStream.Position = 0;
Claybourne answered 2/10, 2015 at 15:52 Comment(0)
C
0

You should rewind MemoryStream to beginning before passing it to response. But you'd better use 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;
Claus answered 2/10, 2015 at 15:53 Comment(5)
What's the warrant for using PushStreamContent?Bloodshed
No need to allocate extra memory for MemoryStream.Claus
In testing your code it comes through inline, not as an attachment. Any ideas as to why?Bloodshed
Also it seems to hang, with a spinning wheel in the tab header.Bloodshed
As to content-disposition - check via http capture which headers are sent. About "hanging" - can't really tell without debugging.Claus

© 2022 - 2024 — McMap. All rights reserved.