上传文件在 ApiController c# 中不起作用

问题描述

我有一个 C# 应用程序,带有一个用于上传图像的表单,但调用转到了控制器,我无法获取上传文件Request.Content.IsMimeMultipartContent() 为假,file.Count() = 0file2 为字符串。

@model Form
<div class="form-wrapper">
    <h3>@Model.Title</h3>
    @if (!string.IsNullOrEmpty(Model.Intro))
    {
        <p>@Html.Raw(Model.Intro)</p>
    }

    <form class="form"
          enctype="multipart/form-data"
          novalidate
          data-required-label="@Html.GetLabel("form-required-field")"
          data-required-group-label="@Html.GetLabel("form-choice-makechoice")"
          data-api-endpoint="/api/form">

        <input id="test" name="test" type="file" required/>
        <input type="hidden" name="tcm" readonly value="@Model.TcmUri">
        <p class="form-section form-section--submit">
            <button class="btn-primary--with-icon-internal" type="submit">@Html.GetLabel("form-submit-button")</button>
        </p>
    </form>
</div>


[System.Web.Http.RoutePrefix("api/form")]
public class ApiFormController : ApiController
{
    public ApiFormController()
    {
    }

    [System.Web.Http.Route("")]
    [System.Web.Http.HttpPost]
    public async Task<HttpResponseMessage> Form()
    {
        if (Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var file = HttpContext.Current.Request.Files;
        var requestForm = HttpContext.Current.Request.Form;
        var file2 = requestForm["test"];
    }
}

解决方法

用于此 enctype="multipart/form-data" 的表单标记中的此代码 if (Request.Content.IsMimeMultipartContent())。最好清洗一下。

我修改了代码。第一,不要改变形式。如果答案不起作用,请使用下面表格的定义

第一步

创建 ApiFormController.cs

public class ApiFormController : ApiController
{
    public ApiFormController()
    {
    }

    [System.Web.Http.HttpPost]
    public async Task<HttpResponseMessage> Form()
    {
       var files = HttpContext.Current.Request.Files;

       //one file
       HttpPostedFile postedfile = files.Get("test");

       //multi file
       List<HttpPostedFile> postedfiles = new List<HttpPostedFile>();
       foreach (var item in files)
       {
           postedfiles.Add(files.Get(item.ToString()));
       }
       
       //save file
       postedfile.SaveAs(Path.Combine("~/uploadfiles/",postedfile.FileName));
       return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

第 2 步

创建 WebApiConfig.cs

public static class WebApiConfig
{
   public static void Register(HttpConfiguration config)
   {
     config.MapHttpAttributeRoutes();

     config.Routes.MapHttpRoute(
        name: "DefaultApi",routeTemplate: "api/form",defaults: new { controller = "ApiForm",action = "Form" }
      );
   }
}

第 3 步

在 global.cs 中注册 WebApiConfig 类

protected void Application_Start()
{
     //...........
     GlobalConfiguration.Configure(WebApiConfig.Register);
     //..........
}

第 4 步

创建视图

<form class="form"
         enctype="multipart/form-data" action="/api/form" method="post">

      <input id="test" name="test" type="file" />
      <br />
      <input type="file" name="test1" id="test1" />
      <p class="form-section form-section--submit">
          <button class="btn-primary--with-icon-internal" type="submit">Upload Files</button>
      </p>
</form>