C \ # 파일 업로드 (메모리 넘 침 방지)

5353 단어 C#Wpf
파일 을 업로드 하기 전에 WebClient 의 업로드 방법 을 사 용 했 습 니 다. UploadFile 방법 은 메모리 가 넘 치기 쉽 고 UploadData 방법 이 해결 되 지 않 았 기 때문에 네티즌 의 방법 을 참고 하여 글 의 주요 내용 은 (http://blogs.msdn.com/b/johan/archive/2006/11/15/are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx) 본문 을 수정 하고,직접 사용 가능:
public static string MyUploader(string strFileToUpload, string strUrl,Action<double,double> uploading)
{
   string strFileFormName = "file";
   Uri oUri = new Uri(strUrl);
   string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");

   // The trailing boundary string
   byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r
--"
+ strBoundary + "--\r
"
); //** strBoundary --, ** // The post message header StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBoundary); sb.Append("\r
"
); sb.Append("Content-Disposition: form-data; name=\""); sb.Append(strFileFormName); sb.Append("\"; filename=\""); sb.Append(Path.GetFileName(strFileToUpload)); sb.Append("\""); sb.Append("\r
"
); sb.Append("Content-Type: "); sb.Append("application/octet-stream"); sb.Append("\r
"
); sb.Append("\r
"
); string strPostHeader = sb.ToString(); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); // The WebRequest HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(oUri); oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary; oWebrequest.Method = "POST"; // This is important, otherwise the whole file will be read to memory anyway... oWebrequest.AllowWriteStreamBuffering = false; // Get a FileStream and set the final properties of the WebRequest FileStream oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read); long length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length; oWebrequest.ContentLength = length; Stream oRequestStream = oWebrequest.GetRequestStream(); // Write the post header oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); // Stream the file contents in small pieces (4096 bytes, max). byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))]; int bytesRead = 0; double size=0; while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0) { oRequestStream.Write(buffer, 0, bytesRead); size+=bytesRead; if(uploading!=null)uploading(length ,size); } oFileStream.Close(); // Add the trailing boundary oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length); WebResponse oWResponse = oWebrequest.GetResponse(); Stream s = oWResponse.GetResponseStream(); StreamReader sr = new StreamReader(s); String sReturnString = sr.ReadToEnd(); // Clean up oFileStream.Close(); oRequestStream.Close(); s.Close(); sr.Close(); return sReturnString; }

취소 기능 이 추가 되면 oWebrequest 의 Abort 방법 으로 업로드 요청 을 취소 할 수 있 습 니 다.

좋은 웹페이지 즐겨찾기