使用ajaxfileupload.js插件
html代码:
12 3 4 5
67 8 9
1011 12 4041
文件上传后台处理代码(asp.net版)
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 : IHttpHandler10 {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 //文件保存目录URL19 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 IsReusable89 {90 get91 {92 return true;93 }94 }95 }