現在很多B/S系統的開發都是通過API方式來進行的,一般服務端會開放一個API接口,客戶端調用API接口來實現圖片或文件上傳的功能。
前段時間碰到需要使用POST請求上傳圖片的功能,好久沒寫了,重新整理下函數,方便后續使用。
為了使用的通用性,函數做了一定的封裝,具體代碼如下:
1 public static void UploadImage(string uploadUrl,string imgPath,string fileparameter="file") 2 { 3 HttpWebRequest request = WebRequest.Create(uploadUrl) as HttpWebRequest; 4 request.AllowAutoRedirect = true; 5 request.Method = "POST"; 6 7 string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線 8 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; 9 byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); 10 byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); 11 12 int pos = imgPath.LastIndexOf("/"); 13 string fileName = imgPath.Substring(pos + 1); 14 15 //請求頭部信息 16 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\""+fileparameter+"\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); 17 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); 18 19 FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read); 20 byte[] bArr = new byte[fs.Length]; 21 fs.Read(bArr, 0, bArr.Length); 22 fs.Close(); 23 24 Stream postStream = request.GetRequestStream(); 25 postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); 26 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 27 postStream.Write(bArr, 0, bArr.Length); 28 postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); 29 postStream.Close(); 30 31 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 32 Stream instream = response.GetResponseStream(); 33 StreamReader sr = new StreamReader(instream, Encoding.UTF8); 34 string content = sr.ReadToEnd(); 35 }
使用起來也比較方便,調用方法如下:
UploadImage("圖上上傳接口地址","本地圖片文件路徑","接口提供的上傳參數名稱,沒有默認為file");
例如:UploadImage("http://xxx.com/upload","C:/test.jpg","upload");