2015-10-02 15 views
5

Tôi đang cố gắng trả lại hình ảnh từ tuyến máy chủ, nhưng tôi nhận được dữ liệu là 0 byte. Tôi nghi ngờ nó có cái gì để làm với cách tôi đang sử dụng MemoryStream. Dưới đây là mã của tôi:Không nhận dữ liệu từ đường C#

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

Qua gỡ lỗi Tôi đã xác minh rằng phương pháp PdfToImages là làm việc và rằng imageMemoryStream được lấp đầy với các dữ liệu từ dòng

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

Tuy nhiên trong việc điều hành nó, tôi nhận được một tập tin đính kèm đó là được đặt tên đúng nhưng là 0 byte. Tôi cần thay đổi gì để nhận được toàn bộ tập tin? Tôi nghĩ rằng nó là một cái gì đó đơn giản nhưng tôi không chắc chắn những gì. Cảm ơn trước.

+0

Có thể bạn phải đặt vị trí phát là 0? 'imageMemoryStream.Position = 0;' –

Trả lời

2

Sau khi văn bản cho MemoryStream, Flush nó sau đó thiết lập Position-0:

imageMemoryStream.Flush(); 
imageMemoryStream.Position = 0; 
0

Bạn nên tua lại MemoryStream để đầu trước khi đi qua nó để phản ứng. Nhưng tốt hơn bạn nên sử dụng 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; 
+0

Lệnh nào đang sử dụng 'PushStreamContent'? –

+0

Không cần phải cấp phát bộ nhớ bổ sung cho 'MemoryStream'. –

+0

Trong thử nghiệm mã của bạn nó đi qua nội tuyến, không phải là tệp đính kèm. Bất kỳ ý tưởng nào về lý do tại sao? –

Các vấn đề liên quan