C# HTTP上傳檔案

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   for   sp   

代碼:

/// <summary>/// Http上傳檔案/// </summary>public static string HttpUploadFile(string url, string path){    // 設定參數    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;    CookieContainer cookieContainer = new CookieContainer();    request.CookieContainer = cookieContainer;    request.AllowAutoRedirect = true;    request.Method = "POST";    string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線    request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");    int pos = path.LastIndexOf("\\");    string fileName = path.Substring(pos + 1);    //要求標頭部資訊     StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);    byte[] bArr = new byte[fs.Length];    fs.Read(bArr, 0, bArr.Length);    fs.Close();    Stream postStream = request.GetRequestStream();    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);    postStream.Write(bArr, 0, bArr.Length);    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);    postStream.Close();    //發送請求並擷取相應回應資料    HttpWebResponse response = request.GetResponse() as HttpWebResponse;    //直到request.GetResponse()程式才開始向目標網頁發送Post請求    Stream instream = response.GetResponseStream();    StreamReader sr = new StreamReader(instream, Encoding.UTF8);    //返回結果網頁(html)代碼    string content = sr.ReadToEnd();    return content;}
View Code

接收檔案的代碼:

using System;using System.Web;namespace SWX{    public partial class test2 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            HttpPostedFile file = Request.Files[0];            file.SaveAs(MapPath("\\UploadFile\\" + file.FileName));            Response.Write("Success\r\n");        }    }}
View Code

 

C# HTTP上傳檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.