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博客

相关推荐
“AI国潮设计-小江”几秒前
Python实战 | SDXL批量生成“带炸英歌”国潮IP:从海报到门店落地(附核心Prompt与授权思路)
开发语言·人工智能·python·prompt·aigc
字节渡客2 分钟前
PHP项目复盘:foreach 引用残留造成的诡异数据错乱
开发语言·php
我就是不信5 分钟前
深入理解 Python 虚拟机:字典(dict)的优化
开发语言·python·哈希算法
艾莉丝努力练剑11 分钟前
【QT】系统相关:多线程QThread基础
开发语言·网络·c++·qt·学习·大模型
ysu_031418 分钟前
uv实战指南-从Python版本虚拟环境到pyproject依赖管理
开发语言·python·pip·uv·虚拟环境·包管理·依赖管理
海宇大数据37 分钟前
零信任架构实战:基于海宇身份证OCR构建自动化跨境清关核验网关
人工智能·架构·c#·自动化
東隅已逝,桑榆非晚1 小时前
c++模板进阶
开发语言·c++·笔记·学习
Cc.Y5 小时前
Java零基础入门:字符串深度掌握——从基础API到StringBuilder性能优化
java·开发语言·性能优化
java资料站9 小时前
十一、评估测试
开发语言·人工智能·python
左手の明天10 小时前
SLIP 协议封装与解析详解:原理、C 代码与实战案例
linux·c语言·开发语言·c++