C#实现HTTP上传文件的方法
本文实例讲述了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("\\");
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("\\uploadfile\\" + file.filename));
response.write("success\r\n");
}
}
}
希望本文所述对大家的c#程序设计有所帮助。