Asp.net mvc 4 MVC4-无法在操作上载文件中使用[HttpPost]
请帮助我修复我的代码,为什么我不能在我的操作中使用[HttpPost]。非常感谢 如果不使用[HttpPost],它可以正常工作。 如果使用[HttpPost]=>错误,则显示找不到资源 我的代码如下: 视图:Asp.net mvc 4 MVC4-无法在操作上载文件中使用[HttpPost],asp.net-mvc-4,Asp.net Mvc 4,请帮助我修复我的代码,为什么我不能在我的操作中使用[HttpPost]。非常感谢 如果不使用[HttpPost],它可以正常工作。 如果使用[HttpPost]=>错误,则显示找不到资源 我的代码如下: 视图: @using (Html.BeginForm("Index", "ManageFiles", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true)
@using (Html.BeginForm("Index", "ManageFiles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<input type="file" id="UpFile" name="UpFile" /><input type="submit" value="Start upload" />
}
只需使用如下所示的参数重新编写您的操作。这可能对你有帮助
[HttpPost]
public ActionResult Index(HttpPostedFileBase UpFile)
{
var path = "~/images/upload/";
// upload file
try
{
var upload = Request.Files["UpFile"];
if (upload != null && upload.ContentLength > 0)
{
upload.SaveAs(Server.MapPath(path + upload.FileName));
}
else
{
ModelState.AddModelError("", "The size of file must be between 0 and 2MB");
}
}
catch
{
ModelState.AddModelError("", "Maybe file size too large");
}
// end upload file
return View();
}
您是否尝试过使用jquery上传?我有一个jquery和处理程序的代码示例,如果您想尝试我目前使用的MVC Uploadcheck的一些工作方法,请检查这是否有帮助:我按照您的方式进行了测试,但它也有错误。我不知道为什么在我采取行动之前不能使用[HttpPost]。非常感谢。
//Jquery
function $UploadFile() {
var fileUpload = $("#UpFile").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var options = {};
options.url = "UploadMyFile";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) {
//Your success result here
};
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
}
$("submit").click(function(e){
e.preventDefault();
$UploadFile();
});
//MVC Action
public ActionResult UploadMyFile(){
var Request = context.Request;
try
{
var upload = Request.Files["UpFile"];
if (upload != null && upload.ContentLength > 0)
{
upload.SaveAs(Server.MapPath(path + upload.FileName));
return "Success";
}
else
{
ModelState.AddModelError("", "The size of file must be between 0 and 2MB");
}
}
catch (Exception ex)
{
return "error: " + ex.Message;
}
return null;
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase UpFile)
{
var path = "~/images/upload/";
// upload file
try
{
var upload = Request.Files["UpFile"];
if (upload != null && upload.ContentLength > 0)
{
upload.SaveAs(Server.MapPath(path + upload.FileName));
}
else
{
ModelState.AddModelError("", "The size of file must be between 0 and 2MB");
}
}
catch
{
ModelState.AddModelError("", "Maybe file size too large");
}
// end upload file
return View();
}