1. 程式人生 > 其它 >c# post body檔案上傳 並下載檔案

c# post body檔案上傳 並下載檔案

        /// 使用Post方法上傳檔案
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files">需要上傳的檔案,Key:對應要上傳的Name,Value:本地檔名</param>
        public void Upload(string url, Dictionary<string, string> files)
        {
            HttpWebRequest request 
= (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; Stream postStream = new MemoryStream(); var doUpload = files != null && files.Count > 0;//是否用Form if (doUpload) { //通過表單上傳檔案 string boundary = "
----" + DateTime.Now.Ticks.ToString("x"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; foreach (var file in files) {
try { var fileName = file.Value; using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { var formdata = string.Format(formdataTemplate, file.Key, fileName /*Path.GetFileName(fileName)*/); var formdataBytes = Encoding.ASCII.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要換行 postStream.Write(formdataBytes, 0, formdataBytes.Length); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { postStream.Write(buffer, 0, bytesRead); } } } catch (Exception ex) { throw ex; } } //結尾 var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); postStream.Write(footer, 0, footer.Length); request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); } request.ContentLength = postStream != null ? postStream.Length : 0; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; request.KeepAlive = true; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; if (postStream != null) { postStream.Position = 0; //直接寫入流 Stream requestStream = request.GetRequestStream(); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } postStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { using (var fs = File.Create(@"d:\xx.png")) { int buffer_count = 65536; byte[] buffer2 = new byte[buffer_count]; int size = 0; while ((size = responseStream.Read(buffer2, 0, buffer_count)) > 0) { fs.Write(buffer2, 0, size); } fs.Flush(); } } }