Home > Web Front-end > JS Tutorial > Implementing file upload based on jQuery Ajax_jquery

Implementing file upload based on jQuery Ajax_jquery

WBOY
Release: 2016-05-16 15:08:18
Original
1306 people have browsed it

The example in this article shares the key code for uploading files based on jQuery Ajax for your reference. The specific content is as follows

JS code:

//保存
function btnAdd() {
  var formData = new FormData($("#frm")[0]);

  $.ajax({
    url: "/Admin/ContentManage/SaveEdit",
    type: "POST",
    data: formData,
    contentType: false, //必须false才会避开jQuery对 formdata 的默认处理 XMLHttpRequest会对 formdata 进行正确的处理  
    processData: false, //必须false才会自动加上正确的Content-Type
    success: function (data) {
      if (data == "OK") {
        alert("保存成功");
        $.iDialog("close"); //刷新父页面
      }
      else {
        alert("保存失败:" + data);
      }
    }
  });
}

Copy after login

ASP.NET MVC code-behind:

//首先判断路径是否存在,不存在则创建路径
string path = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["UploadsFiles"], folder + "/" + DateTime.Now.ToString("yyyyMMdd") + "/");
string physicalPath = server.MapPath(path);
if (!Directory.Exists(physicalPath))
{
  Directory.CreateDirectory(physicalPath);
}

HttpPostedFileBase file = request.Files[0];
string newFileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
string savePath = Path.Combine(physicalPath, newFileName);
file.SaveAs(savePath);
fileName = file.FileName;
string url = Path.Combine(path, newFileName);
return url;
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template