C#實(shí)現(xiàn)HTTP上傳文件的方法
本文實(shí)例講述了C#實(shí)現(xiàn)HTTP上傳文件的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
發(fā)送文件代碼如下:
/// <summary>
/// Http上傳文件
/// </summary>
public static string HttpUploadFile(string url, string path)
{
// 設(shè)置參數(shù)
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"); // 隨機(jī)分隔線
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();
//發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回結(jié)果網(wǎng)頁(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("\\UploadFile\\" + file.FileName));
Response.Write("Success\r\n");
}
}
}
希望本文所述對大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
在winform下實(shí)現(xiàn)左右布局多窗口界面的方法
在web頁面上我們可以通過frameset,iframe嵌套框架很容易實(shí)現(xiàn)各種導(dǎo)航+內(nèi)容的布局界面,而在winform、WPF中實(shí)現(xiàn)其實(shí)也很容易,通過本文給大家介紹在winform下實(shí)現(xiàn)左右布局多窗口界面的方法,本文介紹的非常詳細(xì),對winform布局相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧2016-02-02深入分析C#連接Oracle數(shù)據(jù)庫的連接字符串詳解
本篇文章是對C#連接Oracle數(shù)據(jù)庫的連接字符串進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C# 利用AForge實(shí)現(xiàn)攝像頭信息采集
這篇文章主要介紹了C# 如何利用AForge實(shí)現(xiàn)攝像頭信息采集,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07Unity封裝延時(shí)調(diào)用定時(shí)器
這篇文章主要為大家詳細(xì)介紹了Unity封裝延時(shí)調(diào)用定時(shí)器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04