简体   繁体   English

使用HttpClient将文件上传到ASP.NET WebApi 2

[英]Upload Files with HttpClient to ASP.NET WebApi 2

I have this HttpClient for posting files: 我有这个HttpClient用于发布文件:

var content = new MultipartFormDataContent(Guid.NewGuid().ToString())
{
    new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json")
};

foreach (var file in files)
{
    var byteContent = new ByteArrayContent(file.Data);

    content.Add(byteContent, file.FieldName, file.FileName);
}

return await _client.PostAsync(_apiUrl + apiRelativeUrl, content);

But my ASP.NET WebApi Controller gives error 500 with this exception: 但是我的ASP.NET WebApi Controller给出了以下错误500:

System.IO.IOException: Unexpected end of MIME multipart stream. MIME multipart message is not complete.

The WebApi controller code is WebApi控制器代码为

if (Request.Content.IsMimeMultipartContent())
{
    var multipart = await Request.Content.ReadAsMultipartAsync(); //this line throws the exception
    var fileContent = multipart.Contents.FirstOrDefault();

    if (fileContent != null)
    {
        var photo = await fileContent.ReadAsByteArrayAsync();
    }
}

What am I doing wrong? 我究竟做错了什么?

Basically I used a custom stream to append the newline that asp.net web api is expecting. 基本上,我使用自定义流来附加asp.net Web API期望的换行符。

Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
MemoryStream tempStream = new MemoryStream();
reqStream.CopyTo(tempStream);



tempStream.Seek(0, SeekOrigin.End);
StreamWriter writer = new StreamWriter(tempStream);
writer.WriteLine();
writer.Flush();
tempStream.Position = 0;


 StreamContent streamContent = new StreamContent(tempStream);
 foreach(var header in Request.Content.Headers)
 {
     streamContent.Headers.Add(header.Key, header.Value);
 }

// Read the form data and return an async task.
 await streamContent.ReadAsMultipartAsync(provider);

and add following code in web.config 并在web.config中添加以下代码

<system.web>
    <httpRuntime maxRequestLength="30000000" />
</system.web>

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="30000000" />
      </requestFiltering>
    </security>
</system.webServer>

Hope this helps. 希望这可以帮助。

Try add header of the files type you upload like this: 尝试添加您上传的文件类型的标头,如下所示:

 byteContent.Headers.ContentType =
            MediaTypeHeaderValue.Parse("image/jpeg");

This works fine for me. 这对我来说很好。

I created two new empty projects, one for webapi and one for httpclient. 我创建了两个新的空项目,一个用于webapi,一个用于httpclient。

I tried copying the existing client code and the existing server code to the new projects. 我尝试将现有的客户端代码和现有的服务器代码复制到新项目中。

I discovered that the problem was the parameter to the webapi action, it seems to broke the stream. 我发现问题出在webapi动作的参数上,似乎中断了流。

So if someone need to upload multipart form data to ASP.NET WebApi don't use parameters in the action, it won't resolve any model and it broke the multipart stream. 因此,如果有人需要将多部分表单数据上传到ASP.NET WebApi,则不要在操作中使用参数,它不会解析任何模型,并且会破坏多部分流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM