利用FormData Ajax上传文件

发布于 2017-12-02  141 次阅读


//formFileName: input file的name=""
//方法一
function UploadImg(formID, imgID, hideID, formFileName) {
 var formData = new FormData($("#" + formID)[0]);
 $.ajax({
 url: '/Handlers/ImgUpload.ashx?formFileName=' + formFileName,
 type: 'POST',
 data: formData,
 dataType:"json",
 async: false,
 cache: false,
 contentType: false,
 processData: false,
 dataType: "json",
 success: function (data) {
 $("#" + imgID).attr("src", data);
 $("#" + imgID).show();
 $("#" + hideID).val(data);
 alert("上传成功");
 },
 error: function (err) {
 console.log(err);
 alert("上传失败");
 }
 });
}

//调用方法
 UploadImg("form1", "imgExhibition", "hideExhibition", "newsImg");

//方法二
$("#excelFile").change(function () {
                var fileObj = document.getElementById("excelFile").files[0]; // js 获取文件对象
                if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                    alert("请选择excel文件");
                    return;
                }
                var formFile = new FormData();
                formFile.append("excelFile", fileObj); //加入文件对象 后台通过这个excelFile获取文件对象
                var data = formFile;
                $.ajax({
                    url: "URL",
                    data: data,
                    type: "Post",
                    dataType: "json",
                    async: false,
                    cache: false,//上传文件无需缓存
                    processData: false,//用于对data参数进行序列化处理 这里必须false
                    contentType: false, //必须
                    success: function (data) {

                    },
                })
            })

ASHX接收数据

 public void ProcessRequest(HttpContext context)
 {
 //文件保存目录路径
 string savePath = "/Upload/" + DateTime.Now.ToString("yyyyMMdd");
 string formFileName = context.Request["formFileName"];
 HttpPostedFile imgFile;
 if (!string.IsNullOrEmpty(formFileName))
     imgFile = context.Request.Files[formFileName];
 else
     imgFile = context.Request.Files["fileImg"];
 //最大文件大小30M
 int maxSize = 1024 * 1024 * 30;
 if (imgFile.InputStream.Length > maxSize)
 {
 context.Response.Write("0");
 }
 string dirPath = context.Server.MapPath(savePath);
 string fileExt = Path.GetExtension(imgFile.FileName).ToLower();
 string filename = DateTime.Now.ToString("yyMMddhhmmssff") + fileExt;
 if (!Directory.Exists(dirPath))
 Directory.CreateDirectory(dirPath);
 imgFile.SaveAs(Path.Combine(dirPath, filename));
 string imgUrl = savePath + "/" + filename;
 var result = new
 {
 imgUrl = imgUrl,
 };
 context.Response.Write(JsonHelper.ObjectToJson(result));
 }

LoneKing