標籤:
jQuery-File-Upload 檔案地址
jQuery-File-Upload-master.zip
| 123456789101112131415161718192021222324 |
[HttpGet][HttpPost]public HttpResponseMessage Upload(){ // Get a reference to the file that our jQuery sent. Even with multiple files, they will all be their own request and be the 0 index HttpPostedFile file = HttpContext.Current.Request.Files[0]; // do something with the file in this space // {....} // end of file doing this.SaveAs(HttpContext.Current.Server.MapPath("~/Images/") + file.FileName, file); // Now we need to wire up a response so that the calling script understands what happened HttpContext.Current.Response.ContentType = "text/plain"; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var result = new { name = file.FileName }; HttpContext.Current.Response.Write(serializer.Serialize(result)); HttpContext.Current.Response.StatusCode = 200; // For compatibility with IE‘s "done" event we need to return a result as well as setting the context.response return new HttpResponseMessage(HttpStatusCode.OK);} |
這其中主要是通過解析Http要求標頭中的Content-Range屬性來獲知此次處理的檔案片斷,後續就是基本的檔案操作了,沒什麼可說的。
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
private void SaveAs(string saveFilePath, HttpPostedFile file){ long lStartPos = 0; int startPosition = 0; int endPosition = 0; var contentRange=HttpContext.Current.Request.Headers["Content-Range"]; //bytes 10000-19999/1157632 if (!string.IsNullOrEmpty(contentRange)) { contentRange = contentRange.Replace("bytes", "").Trim(); contentRange = contentRange.Substring(0, contentRange.IndexOf("/")); string[] ranges = contentRange.Split(‘-‘); startPosition = int.Parse(ranges[0]); endPosition = int.Parse(ranges[1]); } System.IO.FileStream fs; if (System.IO.File.Exists(saveFilePath)) { fs = System.IO.File.OpenWrite(saveFilePath); lStartPos = fs.Length; } else { fs = new System.IO.FileStream(saveFilePath, System.IO.FileMode.Create); lStartPos = 0; } if (lStartPos > endPosition) { fs.Close(); return; } else if (lStartPos < startPosition) { lStartPos = startPosition; } else if (lStartPos > startPosition && lStartPos < endPosition) { lStartPos = startPosition; } fs.Seek(lStartPos, System.IO.SeekOrigin.Current); byte[] nbytes = new byte[512]; int nReadSize = 0; nReadSize = file.InputStream.Read(nbytes, 0, 512); while (nReadSize > 0) { fs.Write(nbytes, 0, nReadSize); nReadSize = file.InputStream.Read(nbytes, 0, 512); } fs.Close(); } |
MVC斷點續傳