使用PostAsync从HTML表单上传文件

时间:2015-04-14 15:42:17

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

我想简单地使用WebAPI将文件上传到服务器。我想在我的MVC HomeController中调用WebApi。当我直接使用WebAPI时,它会完美地上传文件,但是当我想使用PostAsync在我的Controller中调用WebAPI时,它不会出于某种原因将文件发送到api。

这是我的MVC控制器中的操作:

 public async Task<ActionResult> Upload(HttpPostedFileBase upload)
    {
        ViewBag.Title = "Upload Files";
        if (upload != null && upload.ContentLength > 0)
        {

            var client = new HttpClient();

            string FullUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + ":" + Request.Url.Port + "/api/values";
            StringContent httpcontent = new StringContent(upload.FileName);

            var response = await client.PostAsync(FullUrl, httpcontent);

            var result = await response.Content.ReadAsAsync<HttpResponseMessage>();

        }


        return View();
    }

这是.cshtml文件:

<form name="form1" method="post" action="/Home/Upload" enctype="multipart/form-data">

<div>
    <label for="upload">Choose a File</label>
    <input name="upload" type="file" />
</div>
<div>
    <input type="submit" value="Submit" />
</div>

最后这是WebApi控制器:

 [HttpPost]
    public HttpResponseMessage PostFile()
    {
        HttpResponseMessage result = null;
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = HttpContext.Current.Server.MapPath("~/Files/" + postedFile.FileName);
                postedFile.SaveAs(filePath);
            }
            result = Request.CreateResponse(HttpStatusCode.Created);
        }
        else
        {
            result = Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        return result;
    }

1 个答案:

答案 0 :(得分:2)

当内容通过表单发布时,它会将multipart / form-data内容类型设置为请求。 您可以尝试明确地将请求内容类型设置为 multipart / form-data

var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(upload.InputStream);
fileContent.Headers.ContentType = upload.ContentType;
requestContent.Add(fileContent, upload.FileName, upload.FileName);

client.PostAsync(url, requestContent);