采用Ajax Post的方式同时上传文件并提交表单,不采用Form表单的Submit方法提交。采用方法如下:
一、js库文件:
function ajaxUploadFile(url, formData,success, complete) {
$.ajax({
url: url,
method: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: formData,
//encType: 'multipart/form-data',
cache: false,
success: function (data) {
success(data);
},
error: function (err) {
err.statusText && alert(err.statusText);
},
complete: function (e) {
complete(e);
}
})
}
二、前台
2.1、引入js库文件后使用方法:
SubmitSave: function () {
var _this = this;
if (!!document.getElementById("file1").value) {
var formData = new FormData();
formData.append('file1', document.getElementById("file1").files[0]);
var uploadUrl = '@Url.Action("FileUpload")';
var successAction = _this.UpdateCertificate;
var completeAction = () => { _this.loading = false; };
_this.loading = true;
ajaxUploadFile(uploadUrl, formData, successAction, completeAction);
}
else {
_this.UpdateCertificate();
}
},
UpdateCertificate: function (upCallbackData) {
this.loading = true;
if (upCallbackData) {
if (upCallbackData.Success) {
this.CertificateFormObj.RawName = upCallbackData.Data.RawName;
this.CertificateFormObj.SystemGivenName = upCallbackData.Data.SystemGivenName;
} else {
this.$message({ type: 'error', message: upCallbackData.Message });
return;
}
}
var _this = this;
jp.createRpc('@Url.Action("UpdateCertificate", "Vendor")')(_this.CertificateFormObj)
.done(function (result) {
_this.showEditCertificateDialog = false;
_this.loadCertificatesByVendorId();
_this.loading = false;
});
}
2.2、页面可以采用隐藏原始File HTML元素,由Button控制:
clickFile:function () {
document.getElementById("file1").click();
},
onUploadFileChange: function (e) {
this.CertificateFormObj.RawName = e.target.value;
},
三、后台方法如下:
[HttpPost]
public ActionResult UpdateCertificate(JObject info)
{
...
int id=_vendorBll.UpdateCertificate(info);
var reslt = new { ItemId = id };
string resultStr = JsonConvert.SerializeObject(reslt);
return Content(resultStr);
}
[HttpPost]
public ActionResult FileUpload()
{
ReponseBase message = new ReponseBase();
try
{
var postedFile = Request.Files.Count > 0 ? Request.Files[0] : null;
if (postedFile == null)
{
message.Message = "No Upload File Can Be Found";
return Json(message);
}
string extension = System.IO.Path.HasExtension(postedFile.FileName) ? System.IO.Path.GetExtension(postedFile.FileName) : "";
string fileName = Guid.NewGuid().ToString("N") + extension;
string url = "/uploads/" + fileName;
string fileFullName = Server.MapPath("~" + url);
string directoryName = System.IO.Path.GetDirectoryName(fileFullName);
if (!System.IO.Directory.Exists(directoryName))
{
System.IO.Directory.CreateDirectory(directoryName);
}
postedFile.SaveAs(fileFullName);
//保存到数据库
/*Sample:
string contractID = Request.Form["ContractID"].ToString();
string typeID = Request.Form["TypeID"].ToString();
_BLL.InsertSupportFile(contractID, Util.Common.GetCurrentAdUser().UID, System.IO.Path.GetFileName(postedFile.FileName), url, typeID);
*/
message.Success = true;
message.Message = "Upload Success";
message.Data = new { RawName = System.IO.Path.GetFileName(postedFile.FileName), SystemGivenName=fileName };
return Json(message);
}
catch (Exception ex)
{
message.Message = String.Format("Upload File Error! --{0}", ex.Message);
return Json(message);
}
}
参考:jQuery+ajax使用FormData方式上传文件到服务器:https://blog.csdn.net/zimu_2080/article/details/89670345