I have an AJAX file upload by call to MVC C# driver, but the browser refreshes and reloads the page.
But if I comment the line that saves the file in the driver does not happen that is only when the file is saved on the server. File.SaveAs (fname);
MVC controller:
[HttpPost]
public ActionResult UploadDocument()
{
if (Request.Files.Count > 0)
{
try
{
FileUpdateDto fileModal = new FileUpdateDto();
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
string fname;
DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Content/Document/" + UserId).ToString());
if (!directory.Exists)
{
Directory.CreateDirectory(Server.MapPath("~/Content/Document/" + UserId).ToString());
}
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
var guidnew = Guid.NewGuid();
fname = Path.Combine(Server.MapPath("~/Content/Document/" + UserId), guidnew + "." + fname.Split('.')[1].ToString());
fileModal.FileName = fname;
fileModal.Path = directory.ToString();
fileModal.DateFileUpload = DateTime.Now;
file.SaveAs(fname); // If I comment this line without refreshing the browser but does not save the file
}
return Json(fileModal);
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Call Ajax in JavaScript:
UploadDocument: function () {
if (window.FormData !== undefined) {
var fileUpload = $("#AdviserFileUpload").get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
//fileData.append('username', 'Manas');
$.ajax({
url: site.baseUrl + '/Api/Upload/Document',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
__this._AdviserDocumentFile = result;
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…