js 原生 ajax 异步上传图片
<script type="text/javascript"> function upload() { var file1 = document.getElementById("file1"); postFile(file1.files[0]); } function postFile(data) { //1.创建异步对象(小浏览器) var req = new XMLHttpRequest(); //2.设置参数 req.open("post", "/API/ImgUp.ashx", true); //3.设置 请求 报文体 的 编码格式(设置为 表单默认编码格式) req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //4.设置回调函数 req.onreadystatechange = function () { //请求状态readyState=4准备就绪,服务器返回的状态码status=200接收成功 if (req.readyState == 4 && req.status == 200) { if (req.responseText != "error") { //changeName(req.responseText); $("#img").attr("src", req.responseText); } } }; //4.发送异步请求 req.send(data);//post传参在此处 } </script> <body> <input id="file1" type="file" value="选择文件" /> <input id="btnUp" onclick="upload()" type="button" value="上传" /> <img id="img" src="" /> </body>
后台ashx处理
public void ProcessRequest(HttpContext context) { //context.Request["data"] Stream stream = new BufferedStream(context.Request.InputStream); byte[] buffer=new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); string path = context.Server.MapPath("/ImgUp/") + "1.jpg"; File.WriteAllBytes(path, buffer); context.Response.Write("/ImgUp/1.jpg"); }
* 使用 ajaxfileupload.js 异步上传
1 <script src="Scripts/jquery-2.1.4.min.js"></script> 2 <script src="Scripts/ajaxfileupload.js"></script> 3 <script type="text/javascript"> 4 function upload2() { 5 $.ajaxFileUpload 6 ( 7 { 8 url: '/API/ImgUp2.ashx', //用于文件上传的服务器端请求地址 9 secureuri: false, //是否需要安全协议,一般设置为false 10 fileElementId: 'file1', //文件上传域的ID 11 dataType: 'html', //返回值类型 一般设置为json 12 success: function (data, status) //服务器成功响应处理函数 13 { 14 alert("ok"); 15 //$("#img1").attr("src", data.imgurl); 16 //if (typeof (data.error) != 'undefined') { 17 // if (data.error != '') { 18 // alert(data.error); 19 // } else { 20 // alert(data.msg); 21 // } 22 //} 23 }, 24 error: function (data, status, e)//服务器响应失败处理函数 25 { 26 alert("error"); 27 } 28 } 29 ) 30 return false; 31 } 32 33 </script> 34 35 36 <body> 37 <form id="form1" > 38 <input id="file1" name="file1" type="file" value="选择文件" /> 39 <input id="btnUp" onclick="upload2()" type="button" value="上传" /> 40 <img id="img" src="" /> 41 </form> 42 </body>