HttpWebRequest上傳文件(Excel等)

   
//上傳代碼
/// <summary> /// 文件上傳 /// </summary> /// <param name="strAddress">路徑地址,不包括服務地址</param> /// <param name="postedFile"></param> /// <returns></returns> public static IResponseResult HttpPostFile(string strAddress, HttpPostedFile postedFile,string reFileName) { string url = ConfigHelper.GetConfigString("PAOfferSystemAddress") + strAddress; //1>建立請求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //2>Cookie容器(保存cookie,只是上傳文件,則能夠註釋掉) //request.CookieContainer = cookieContainer; request.Method = "POST"; request.Timeout = 120000; request.Credentials = System.Net.CredentialCache.DefaultCredentials; request.KeepAlive = true; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");//分界線 byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary;//內容類型 //3>表單數據模板 //string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; //4>讀取流 byte[] buffer = new byte[postedFile.ContentLength]; postedFile.InputStream.Read(buffer, 0, buffer.Length); //5>寫入請求流數據 string strHeader = "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n"; strHeader = string.Format(strHeader, "filedata", //postedFile.FileName, reFileName + postedFile.FileName, postedFile.ContentType); //6>HTTP請求頭 byte[] byteHeader = System.Text.ASCIIEncoding.UTF8.GetBytes(strHeader); StringBuilder sbBody=new StringBuilder (); sbBody.Append(System.Text.Encoding.UTF8.GetString(boundaryBytes)); sbBody.Append(System.Text.Encoding.UTF8.GetString(byteHeader)); sbBody.Append(System.Text.Encoding.UTF8.GetString(buffer)); sbBody.Append(System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"))); string headValue = Encrpt(sbBody.ToString());//加密 request.Headers.Add("OfferServiceAuthorization", headValue); request.Headers.Add("CustomID", ConfigurationManager.AppSettings["CustomID"]); try { using (Stream stream = request.GetRequestStream()) { #region 寫入請求流(表單數據) //寫入請求流(表單數據) //if (null != parameters) //{ // foreach (KeyValuePair<string, object> item in parameters) // { // stream.Write(boundaryBytes, 0, boundaryBytes.Length);//寫入分界線 // byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, item.Key, item.Value)); // stream.Write(formBytes, 0, formBytes.Length); // } //} #endregion //6.0>分界線============================================注意:缺乏次步驟,可能致使遠程服務器沒法獲取Request.Files集合 stream.Write(boundaryBytes, 0, boundaryBytes.Length); //6.1>請求頭 stream.Write(byteHeader, 0, byteHeader.Length); //6.2>把文件流寫入請求流 stream.Write(buffer, 0, buffer.Length); //6.3>寫入分隔流 byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); stream.Write(trailer, 0, trailer.Length); //6.4>關閉流 stream.Close(); } string responseContent = ""; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { responseContent = streamReader.ReadToEnd(); response.Close(); request.Abort(); } return JsonConvertHelper.DataContractToModel<IResponseResult>(responseContent); } catch (Exception ex) { throw new Exception(ex.Message); } }

//服務器代碼
   HttpPostedFile file = Context.Request.Files["filedata"];//獲取上傳文件
            if (null == file || file.ContentLength == 0)
            {
                IResponseResult responseResult = new IResponseResult();
                responseResult.Status = ResponseStatus.Fail;
                responseResult.Message = "Upload file is invalid";
                //to json返回結果
                string toJson = JsonConvertHelper.ToJson(responseResult);
                Response.Write(toJson);
            }
            else
            {
                string filePath = Server.MapPath("~/File/Excel");
                if (!Directory.Exists(filePath))//判斷文件夾是否存在 
                {
                    Directory.CreateDirectory(filePath);//不存在則建立文件夾 
                }
                file.SaveAs(string.Format("{0}/{1}", filePath, file.FileName));
                IResponseResult responseResult = new IResponseResult();
                responseResult.Status = ResponseStatus.Success;
                string toJson = JsonConvertHelper.ToJson(responseResult);
                Response.Write(toJson);
            }
相關文章
相關標籤/搜索