无法在从MVC控制器进行发布的同时在web Api中获取整个图像?
问题描述:
实际上,我正在将图像作为从MVC控制器到Web API的内存流作为MemoryStream发送,同时在Web API中下载图像时,我只是获取了一半图像而不是完整图像。 Please find the sample output Image in this link无法在从MVC控制器进行发布的同时在web Api中获取整个图像?
我的MVC控制器:
public ActionResult Index(FormCollection formCollection)
{
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
if (file.ContentLength > 0)
{
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
ms.Position = 0;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:35221");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octent-stream"));
HttpContent content = new StreamContent(ms);
var response = client.PostAsync("Api/Ocr/GetText",content).Result;
if (response.IsSuccessStatusCode)
{
}}}}
我的Web API控制器:
[HttpPost]
public List<string> GetText(HttpRequestMessage request)
{
try
{
HttpContent content = Request.Content;
MemoryStream ms = new MemoryStream();
content.CopyToAsync(ms);
Stream stream = ms;
Bitmap bmp = new Bitmap(stream);
bmp.Save(@"C:\Users\bPopuri\Desktop\Test\Temp.jpg");
byte[] value = memorystream.ToArray();
}
对不起你们,我不能在这里发表我的总的代码。我只是将图像从MVC发送到Web API,但Web API中的图像未正确加载。
请帮我解决这个问题。
在此先感谢您的帮助
答
你需要你的电话await
到CopyToAsync
。为了做到这一点,做如下修改:
public async Task<List<string>> GetText(HttpRequestMessage request)
{
...
await content.CopyToAsync(ms);
...
}
它看起来像问题是由于您试图保存文件之前没有完成的复制操作。
那么你正在使用'Async'方法。我猜测在你尝试使用它之前没有进行复制。您需要确保首先完成“异步”操作。 –
@ stephen.vakil感谢您的帮助! – Bhargav