[英]Upload file using Ajax call using ASP.NET MVC
I would like to upload a file in my page using: 我想使用以下方式在页面中上传文件:
<input type="file" name="FileName">
I have a button, clicking on which an ajax post is done. 我有一个按钮,单击完成的ajax发布。
$.ajax({
cache: false,
async: true,
type: "POST",
url: '@Url.Content("~/OCR/OCRProcessor")',
data: '',
success: function (data) {
$('#ocrresult').val(data);
}
});
I would like to get the file uploaded in the controller action method something like below: 我想在控制器操作方法中上传文件,如下所示:
HttpPostedFileBase hpf = Request.Files["FileName"] as HttpPostedFileBase
Please let me know the optimal way to achieve this task. 请让我知道完成此任务的最佳方法 。
jquery Forms plugin ( GitHub Link )would be an ideal choice in this context. 在这种情况下,jquery Forms插件 ( GitHub链接 )将是理想的选择。 You can simply do it like this.
您可以像这样简单地做到这一点。 (Include the file input in this form)
(包括以这种形式输入的文件)
$('#myFormId').submit(function() {
// submit the form
$(this).ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
This would be a No plugin approach (only in Html5), but I'm still recommending the plugin 这将是一个无插件的方法(仅在Html5中使用),但我仍建议该插件
$("#myFormId").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "YourPath/ToAction",
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Code show here 代码显示在这里
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var fileData = new FormData();
fileData.append('Type', Type ); //other requered pass data
fileData.append('name', dataRow.CustomerName); //other requered pass data
fileData.append('Id', dataRow.InvoiceId); //other requered pass data
fileData.append('subject', Sub); //other requered pass data
fileData.append('message', Mess); //other requered pass data
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '/Email/SendEmail',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (data) {
if (data == "No") {
alert("Email Not Exist in Customer Master." );
}
if (data == "Not") {
alert("Email Not Exist in System Setting.");
}
if (data == "NotExist") {
alert("File Not Exist or Some Other Error");
}
if (data == "PassNot") {
alert("Email Password Not Exist in System Setting.");
}
if (data == "NotFile") {
$('btn-Print').trigger('click');
}
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.