国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#實現HTTP上傳文件的方法

2020-01-24 02:18:03
字體:
來源:轉載
供稿:網友

本文實例講述了C#實現HTTP上傳文件的方法。分享給大家供大家參考。具體實現方法如下:

發送文件代碼如下:

復制代碼 代碼如下:

/// <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("http://");
    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;
}

接收文件的代碼如下:

復制代碼 代碼如下:

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("http://UploadFile//" + file.FileName));
            Response.Write("Success/r/n");
        }
    }
}

希望本文所述對大家的C#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邻水| 竹山县| 四会市| 茶陵县| 江孜县| 三原县| 万州区| 个旧市| 龙南县| 玉屏| 武宁县| 高州市| 鹤岗市| 淮南市| 左权县| 大城县| 黑河市| 成安县| 东光县| 革吉县| 唐河县| 肥东县| 武宣县| 孟连| 文昌市| 衡东县| 长泰县| 唐海县| 黄冈市| 手游| 元江| 卓尼县| 曲阳县| 尚义县| 永平县| 珲春市| 微山县| 都匀市| 武威市| 宿迁市| 克山县|