首页 > 代码库 > C# HTTP上传文件

C# HTTP上传文件

using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Net;using System.Text;using System.IO;/// <summary>///HttpUploadDemo 的摘要说明/// </summary>public class HttpUploadDemo{    public HttpUploadDemo()    {        }    /// <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);        string headContent = string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName);        //请求头部信息        StringBuilder sbHeader = new StringBuilder(headContent);        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();        //"\r\n--" + boundary + "\r\n" 这个byte数据        postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);        //信息头byte 数据 "Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n        postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);        //需要上传文件byte数据        postStream.Write(bArr, 0, bArr.Length);        //添加尾部的时间戳          //\r\n--" + boundary + "--\r\n 这个byte数据        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.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;public partial class httpUpload_Index : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            string url = "http://172.16.1.110:8888/httpUpload/Index.aspx";            string filepath = @"C:\Users\Administrator\Desktop\images\QQ截图20140620081425.png";            string result = HttpUploadDemo.HttpUploadFile3(url, filepath);            Response.Write(result);        }    }}
using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.IO;namespace WebThreadTest.httpUpload{    public partial class Index : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            string password = this.Request["password"];            string loginName = this.Request["loginName"];            HttpPostedFile file = Request.Files[0];            if (file.ContentLength <= 0)            {                return;            }            string filename = file.FileName;            string extension = Path.GetExtension(filename);            string uploadFilename = DateTime.Now.ToFileTime() + extension;            string uploadDic = Server.MapPath(@"~/resource/httpUpload/");            if (!Directory.Exists(uploadDic))            {                Directory.CreateDirectory(uploadDic);            }            file.SaveAs(uploadDic + uploadFilename);            Response.Write("Success\r\n");        }    }}

 

C# HTTP上传文件