我有一个带有表单的c#应用程序来上传图像,但是调用到控制器,我不能上传文件。
Request.Content.IsMimeMultipartContent()
为假,file.Count() = 0
和file2
为字符串。@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())
的形式标签中使用。最好把它清理干净。
我修改了代码。第一,不要改变形式。如果答案不正确,请使用下面表格的定义
步骤1
创建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
<创建视图/em>
<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>