Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Stream an image to a client app in asp.net web api?

I have to retrieve an image from the disk or a web link , resize it and stream it to the client app. This is my controller method.

[HttpPost]
    [ActionName("GetImage")]
    public HttpResponseMessage RetrieveImage(ImageDetails details)
    {
        if (!details.Filename.StartsWith("http"))
        {
            if (!FileProvider.Exists(details.Filename))
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "File not found"));
            }

            var filePath = FileProvider.GetFilePath(details.Filename);

            details.Filename = filePath;
        }                

        var image = ImageResizer.RetrieveResizedImage(details);

        MemoryStream stream = new MemoryStream();

        // Save image to stream.
        image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);        

        var response = new HttpResponseMessage();
        response.Content = new StreamContent(stream);
        response.Content.Headers.ContentDisposition
            = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = details.Filename;
        response.Content.Headers.ContentType
            = new MediaTypeHeaderValue("application/octet-stream");

        return response;
    }

And this is how am sending the web link(in this case) and receiving the image at the client app end.

HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:27066");
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/octet-stream"));

            ImageDetails img = new ImageDetails { Filename = "http://2.bp.blogspot.com/-W6kMpFQ5pKU/TiUwJJc8iSI/AAAAAAAAAJ8/c3sJ7hL8SOw/s1600/2011-audi-q7-review-3.jpg", Height = 300, Width = 200 };

            var response = await client.PostAsJsonAsync("api/Media/GetImage", img);
            response.EnsureSuccessStatusCode(); // Throw on error code.

            var stream = await response.Content.ReadAsStreamAsync();

            FileStream fileStream = System.IO.File.Create("ImageName");
            // Initialize the bytes array with the stream length and then fill it with data
            byte[] bytesInStream = new byte[stream.Length];
            stream.Read(bytesInStream, 0, (int)bytesInStream.Length);    
            // Use write method to write to the specified file
            fileStream.Write(bytesInStream, 0, (int) bytesInStream.Length);



            MessageBox.Show("Uploaded");

The image is being retrieved from the web link and the resizing is done properly but am not sure if its being streamed proeprly as its creating a 0kb file with "ImageName" when received at client app. Can anyone please tell me where am going wrong? I have been banging my head about it all day :(

like image 943
Bitsian Avatar asked Feb 03 '26 22:02

Bitsian


1 Answers

Try resetting the position of the memory stream before passing it to the response:

stream.Position = 0;
response.Content = new StreamContent(stream);

I suppose that your image resizing library is leaving the position of the memory stream at the end.

like image 191
Darin Dimitrov Avatar answered Feb 06 '26 11:02

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!