问题描述
在我的项目中,我需要上传一个文本文件.我们正在使用MVC4-Razr.我想使用AJAX/Jquery/Javascript文件上传,因为它不会发回到表单中.这是我的代码.它实际上是在上传文件,但之后它会重定向到reports \ uploadfile的值将为true.有没有更好的方法可以做到这一点.
In My project I need to upload a text file.We are using MVC4 - Razr.I want to use AJAX/Jquery/Javascript file upload as It doesn't post back to the form.Here is my code. Its actually uploading the file but after that it redirectsto reports\uploadfile will the value true.Is there any better way of doing this.
这是我的代码@@@@@@@@@@
Here is my code@@@@@@@@@
@using (Html.BeginForm("uploadfile", "reports", FormMethod.Post, new {enctype = enter code here`"multipart/form-data"}))
{
<input type="file" name="FileUpload1" /><br/>
<input type="submit" name ="Submit" id="Uploadfile" value="Upload"/>
}
-控制器代码
[HttpPost]
public JsonResult UploadReports()
{
if (Request.Files[0].ContentLength > 0)
{
string uploadPath = "C:\\Upload";
string filename = Path.GetFileName(Request.Files[0].FileName);
Request.Files[0].SaveAs(Path.Combine(uploadPath, filename));
}
return Json(true);
}
推荐答案
我认为最简单的方法是利用 jQuery表单插件.这样,您就可以按如下所示取消文件上传:
The easiest way in my opinion is to utilize jQuery Form Plugin. This way you can ajaxify file upload as below:
<script type="text/javascript">
$(function () {
$('#myForm').ajaxForm({
});
});
</script>
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { @id = "myForm", enctype = "multipart/form-data" }))
{
<input type="file" name="FileUpload1" /><br />
<input type="submit" name="Submit" id="Uploadfile" value="Upload" />
}
在公共UploadReports
方法中,您可以接受FileUpload1
参数:List<HttpPostedFileBase> FileUpload1
And in the public UploadReports
method you can accept FileUpload1
parameter: List<HttpPostedFileBase> FileUpload1
这篇关于MVC中的AJAX上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!