如何在asp.net web api中将图像流式传输到客户端应用程序?

时间:2012-12-04 06:32:41

标签: c# asp.net asp.net-mvc streaming asp.net-web-api

我必须从磁盘或Web链接中检索图像,调整其大小并将其流式传输到客户端应用程序。这是我的控制器方法。

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

这就是发送网络链接(在这种情况下)并在客户端应用程序端接收图像的方式。

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");

正在从网络链接中检索图像,并且调整大小已正确完成,但我不确定它是否正在流式传输,因为它在客户端应用程序收到时会创建一个带有“ImageName”的0kb文件。谁能告诉我哪里出错了?我一整天都在喋喋不休地说:(

1 个答案:

答案 0 :(得分:3)

尝试在将内存流传递给响应之前重置内存流的位置:

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

我想你的图像大小调整库最后会留下内存流的位置。