将MultipartFormDataContent从Controller Action Method发布到WebApi Post方法

时间:2017-02-13 19:55:55

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

在我的ASP.NET MVC项目中,我试图将图像从Controller动作方法发布到API控制器方法。 Plan是将此API用于其他客户端以上传图像。

我能够从Controller Action方法成功点击API Post方法,但无法传递图像对象。

这是我的HomeController.cs Upload行动方法

[HttpPost]
public async Task<ActionResult> Upload(FormCollection formCollection)
{
    var baseUri = "http://localhost/api/Process";

    HttpPostedFileBase file = Request?.Files[0];

    if (file == null || (file.ContentLength <= 0) || string.IsNullOrEmpty(file.FileName))
        return new EmptyResult();

    string fileName = file.FileName;
    byte[] fileBytes = new byte[file.ContentLength];

    HttpContent stringContent = new StringContent(fileName);
    HttpContent fileStreamContent = new StreamContent(file.InputStream);
    HttpContent bytesContent = new ByteArrayContent(fileBytes);

    using (var formDataContent = new MultipartFormDataContent())
    {
        formDataContent.Add(stringContent, "fileName", fileName);
        formDataContent.Add(fileStreamContent, "inputStream", fileName);
        formDataContent.Add(bytesContent, "fileBytes", fileName);
        using (var httpClient = new HttpClient())
        {
            formDataContent.Headers.ContentType =
                MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

            var response = await httpClient.PostAsync(baseUri, formDataContent);
            var content = await response.Content.ReadAsStringAsync();
           //Handle the response
        }
    }
    return View("Result");
}

在我继承自ApiController的Process控制器中,我有以下Post方法

[HttpPost]
public async Task<string> Post([FromBody]MultipartFormDataContent formDataContent)
{
    Task<string> imageContent = Request.Content.ReadAsStringAsync();
    string body = imageContent.Result;
    ImageResponse imageResponse = null;
    //.................
    //.................
    return someValue
}

此处参数formDataContent始终为空,Request.Content.ReadAsStringAsync()为空

1 个答案:

答案 0 :(得分:1)

尝试从控制器发送

//...other code removed for brevity

using (var form = new MultipartFormDataContent()) {

    var stringContent = new StringContent("fileToUpload");
    form.Add(stringContent, "fileToUpload");

    var streamContent = new StreamContent(file.InputStream);
    streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);
    streamContent.Headers.ContentLength = file.ContentLength;
    streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
        Name = "fileToUpload",
        FileName = file.FileName
    };
    form.Add(streamContent);

    using (var httpClient = new HttpClient()) {

        var response = await httpClient.PostAsync(baseUri, form);

        //...other code removed for brevity
    }
}

然后通过提取发送的信息在ApiController处理它......

[HttpPost]
public async Task<IHttpActionResult> Post() {
    var content = Request.Content;
    //get file name from content disposition
    var fileName = content.Headers.ContentDisposition.FileName;
    //Get file stream from the request content
    var fileStream = await content.ReadAsStreamAsync();

    //...other code removed for brevity

    return Ok();
}

参考了这个答案:Upload image using HttpClient