我必须从磁盘或网络链接中检索图像,调整其大小并将其流式传输到客户端应用程序。这是我的控制器方法。
[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;
}
这就是发送 Web 链接(在这种情况下)并在客户端应用程序端接收图像的方式。
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");
正在从 Web 链接检索图像并且调整大小已正确完成,但不确定它是否正确流式传输,因为它在客户端应用程序收到时创建了一个带有“ImageName”的 0kb 文件。谁能告诉我哪里出错了?我整天都在为此头疼:(