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#HTTP文件上传和参数_c# http上传文件-CSDN博客

相关推荐
future141230 分钟前
C#学习日记
开发语言·学习·c#
king_harry1 小时前
Java程序-OceanBase Connector/J 示例
开发语言
傻啦嘿哟2 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
翻滚吧键盘2 小时前
js代码09
开发语言·javascript·ecmascript
q567315232 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
rzl022 小时前
java web5(黑马)
java·开发语言·前端
时序数据说3 小时前
为什么时序数据库IoTDB选择Java作为开发语言
java·大数据·开发语言·数据库·物联网·时序数据库·iotdb
jingling5553 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
00后程序员张3 小时前
免Mac上架实战:全平台iOS App上架流程的工具协作经验
websocket·网络协议·tcp/ip·http·网络安全·https·udp
m0_687399843 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg