要使用Jquery异步上载文件,请执行以下步骤:
步骤1在您的项目中,打开Nuget管理器并添加包(jquery fileupload(只需将其写入搜索框,它就会出现并安装))网址:https://github.com/blueimp/jQuery-File-Upload
步骤2在HTML文件中添加以下脚本,这些脚本已通过运行上述包添加到项目中:
jquery.ui.widget.jsjquery.iframe-transport.jsjquery.filepload.js
步骤3按照以下代码编写文件上传控制:
<input id="upload" name="upload" type="file" />
步骤4将js方法编写为uploadFile,如下所示:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
步骤5:在就绪功能中,调用元素文件上传,以启动以下过程:
$(document).ready(function()
{
uploadFile($('#upload'));
});
步骤6根据以下内容编写MVC控制器和操作:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}