ajax结合ashx处理程序实现文件上传
一、ajaxFileUpload是一个异步上传文件的jQuery插件。
ajaxFileUpload参数说明:(copy了别人的参数说明)
1、url 上传处理程序地址。
2,fileElementId 需要上传的文件域的ID,即的ID。
3,secureuri 是否启用安全提交,默认为false。
4,dataType 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success 提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error 提交失败自动执行的处理函数。
7,data 自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8, type 当要提交自定义参数时,这个参数要设置成post
HTML代码:
1
2
3
4
5
6
7
8
9
10
11
12 .file {13 position: relative;14 background-color: #b32b1b;15 border: 1px solid #ddd;16 width: 68px;17 height: 25px;18 display: inline-block;19 text-decoration: none;20 text-indent: 0;21 line-height: 25px;22 font-size: 14px;23 color: #fff;24 margin: 0auto;25 cursor: pointer;26 text-align: center;27 border: none;28 border-radius: 3px;29 }30
31 .file input {32 position: absolute;33 top: 0;34 left: -2px;35 opacity: 0;36 width: 10px;37 }38
39
40 $(function () {41 //选择文件
42 $(".file").on("change", "input[type=‘file‘]", function () {43 var filePath = $(this).val();44 //设置上传文件类型
45 if (filePath.indexOf("xls") != -1 || filePath.indexOf("xlsx") != -1) {
46
47 //上传文件
48 $.ajaxFileUpload({49 url: ‘FileHandler.ashx‘,//处理程序路径
50 secureuri: false,51 fileElementId: ‘btnfile‘,52 dataType: ‘json‘,53 success: function (data, status) {54 //获取上传文件路径55 //$("#txt_filePath").val(data.filenewname);
56 alert("文件上传成功!");57 },58 error: function (data, status, e) {59 //alert(e);
60 alert("not");61 }62 });63
64
65 } else {66 alert("请选择正确的文件格式!");67 //清空上传路径68 $("#txt_filePath").val("");69 return false;70 }
71 });72 })73
74
75
76
77
78
79
83
84
ashx代码:
1
2
3 usingSystem;4 usingSystem.Web;5
6 public classFileHandler : IHttpHandler {7
8 public voidProcessRequest (HttpContext context) {9 //context.Response.ContentType = "text/plain";10 //context.Response.Write("Hello World");
11
12
13 context.Response.ContentType = "text/plain";14 string msg = string.Empty;15 string error = string.Empty;16 string result = string.Empty;17 string filePath = string.Empty;18 string fileNewName = string.Empty;19
20 //这里只能用才能有效果,因为服务器控件是HttpInputFile类型
21 HttpFileCollection files =context.Request.Files;22 if (files.Count > 0)23 {24 //设置文件名
25 fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);26 //保存文件
27 files[0].SaveAs(context.Server.MapPath("~/Upload/" +fileNewName));28 msg = "文件上传成功!";29 result = "{msg:‘" + msg + "‘,filenewname:‘" + fileNewName + "‘}";30 }31 else
32 {33 error = "文件上传失败!";34 result = "{ error:‘" + error + "‘}";35 }36 context.Response.Write(result);37 context.Response.End();38 }39
40 public boolIsReusable {41 get{42 return false;43 }44 }45
46 }
如果想上传多张图片只要给 input 添加一个 multiple 属性
即:
就可以上传多个图片
ajaxFileUpload下载:
链接:https://pan.baidu.com/s/1slkfpOp 密码:5s8r