/// <summary> /// UploadFilesHandler 的摘要说明 /// </summary> public class UploadFilesHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { List<FileReponse> list = new List<FileReponse>(); string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"uploadFile\" + DateTime.Now.Year.ToString() + @"\" + DateTime.Now.Month.ToString() + @"\" + DateTime.Now.Day.ToString() + @"\" + System.Web.HttpUtility.UrlDecode(context.Request.Params["userName"].ToString()) + @"\"; if (context.Request.Files.Count > 0) { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } try { foreach (string files in context.Request.Files) { HttpPostedFile upfile = context.Request.Files[files]; int bufferSize = 1024 * 50;//50K string _guid = Guid.NewGuid().ToString().Replace("-", ""); byte[] buffer = new byte[bufferSize]; int currentCounts = 0;// long totalLength = upfile.ContentLength; string name = upfile.FileName.Substring(upfile.FileName.LastIndexOf("\\") + 1); string fileName = filePath + _guid + "_S_" + name; using (FileStream fs = new FileStream(fileName, FileMode.Create)) { while (currentCounts < totalLength) { int bytes = upfile.InputStream.Read(buffer, 0, bufferSize); fs.Write(buffer, 0, bytes); //Thread.Sleep(1);//0.001s currentCounts += bytes; } } FileReponse item = new FileReponse(); item.Name = name; item.FilePath = fileName; int filepos = item.FilePath.LastIndexOf("uploadFile"); item.FileUrl = item.FilePath.Substring(filepos); list.Add(item); } } catch (Exception ex) { } } string reponse = JsonConvert.SerializeObject(list); context.Response.Write(reponse); //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } } internal class FileReponse { public string Name { get; set; } public string FilePath { get; set; } public string FileUrl { get; set; } }
使用: