ajax图片上传
使用ajaxfileupload.js插件
html代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <p> 2 <label>ajax上传</label> 3 <input type="file" name="fileToUpload" id="fileToUpload" class="inp_fileToUpload" multiple="multiple"/> 4 <img src="$web.site$web.tpl#**#adminht/images/lb_head.jpg" width="30px" height="30px" class="img_upload" id="img" /> 5 </p> 6 <p> 7 <label>最新修改人员:</label> 8 <input readonly="readonly" type="text" size="30" /> 9 </p> 10 <div> 11 12 <script type="text/javascript"> 13 $(function() { 14 $(".inp_fileToUpload").live("change", function() {//现在这个已经适用于多个file表单。 15 ajaxFileUpload($(this).attr("id"), $(this).parent().children(".img_upload").attr("id")); 16 }) 17 }) 18 function ajaxFileUpload(file_id, img_id) { 19 jQuery.ajaxFileUpload({ 20 url : '/upload/upload_json.ashx', //用于文件上传的服务器端请求地址 21 secureuri : false, //是否需要安全协议,一般设置为false 22 fileElementId : file_id, //文件上传域的ID 23 dataType : 'json', //返回值类型 一般设置为json 24 success : function(data, status)//服务器成功响应处理函数 25 { 26 if (data.error == 0) { 27 $("#" + img_id).attr("src", data.url); 28 } else { 29 alert(data.message); 30 } 31 }, 32 error : function(data, status, e)//服务器响应失败处理函数 33 { 34 alert(e); 35 } 36 }) 37 return false; 38 } 39 </script> 40 </div> 41 </div>
文件上传后台处理代码(asp.net版)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ webhandler Language="C#" class="Upload" %> 2 3 using System; 4 using System.Collections; 5 using System.Web; 6 using System.IO; 7 using System.Globalization; 8 using LitJson; 9 public class Upload : IHttpHandler 10 { 11 private HttpContext context; 12 public void ProcessRequest(HttpContext context) 13 { 14 String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); 15 16 //文件保存目录路径 17 String savePath = "attached/"; 18 //文件保存目录URL 19 String saveUrl = aspxUrl + "attached/"; 20 //定义允许上传的文件扩展名 21 Hashtable extTable = new Hashtable(); 22 extTable.Add("image", "gif,jpg,jpeg,png,bmp"); 23 extTable.Add("flash", "swf,flv"); 24 extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); 25 extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); 26 //最大文件大小 27 int maxSize = 1000000; 28 this.context = context; 29 HttpPostedFile imgFile = context.Request.Files["imgFile"]; 30 if (imgFile == null) 31 { 32 showError("请选择文件。"); 33 } 34 String dirPath = context.Server.MapPath(savePath); 35 if (!Directory.Exists(dirPath)) 36 { 37 showError("上传目录不存在。"); 38 } 39 String dirName = context.Request.QueryString["dir"]; 40 if (String.IsNullOrEmpty(dirName)) { 41 dirName = "image"; 42 } 43 if (!extTable.ContainsKey(dirName)) { 44 showError("目录名不正确。"); 45 } 46 String fileName = imgFile.FileName; 47 String fileExt = Path.GetExtension(fileName).ToLower(); 48 if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) 49 { 50 showError("上传文件大小超过限制。"); 51 } 52 if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) 53 { 54 showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"); 55 } 56 //创建文件夹 57 dirPath += dirName + "/"; 58 saveUrl += dirName + "/"; 59 if (!Directory.Exists(dirPath)) { 60 Directory.CreateDirectory(dirPath); 61 } 62 String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); 63 dirPath += ymd + "/"; 64 saveUrl += ymd + "/"; 65 if (!Directory.Exists(dirPath)) { 66 Directory.CreateDirectory(dirPath); 67 } 68 String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; 69 String filePath = dirPath + newFileName; 70 imgFile.SaveAs(filePath); 71 String fileUrl = saveUrl + newFileName; 72 Hashtable hash = new Hashtable(); 73 hash["error"] = 0; 74 hash["url"] = fileUrl; 75 context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); 76 context.Response.Write(JsonMapper.ToJson(hash)); 77 context.Response.End(); 78 } 79 private void showError(string message) 80 { 81 Hashtable hash = new Hashtable(); 82 hash["error"] = 1; 83 hash["message"] = message; 84 context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); 85 context.Response.Write(JsonMapper.ToJson(hash)); 86 context.Response.End(); 87 } 88 public bool IsReusable 89 { 90 get 91 { 92 return true; 93 } 94 } 95 }