C#实现文件的上传

cs 复制代码
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
 
class Program
{
    static async Task Main(string[] args)
    {
        string apiUrl = "http://example.com/upload"; // 替换为你的上传API地址
        string filePath = @"C:\path\to\your\file.txt"; // 替换为你要上传的文件路径
 
        using (var client = new HttpClient())
        using (var form = new MultipartFormDataContent())
        {
            using (var fs = File.OpenRead(filePath))
            using (var stream = new StreamContent(fs))
            {
                var fileName = Path.GetFileName(filePath);
                stream.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                {
                    Name = "file", // 这里的name需要和API端的参数名称一致
                    FileName = fileName
                };
                
                form.Add(stream, "file", fileName); // 这里的"file"需要和API端的参数名称一致
                
                var response = await client.PostAsync(apiUrl, form);
                string responseString = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine(responseString);
            }
        }
    }
}

确保你的API端点能够处理multipart/form-data类型的请求,并且你有权限上传文件到指定的位置。这个例子中的apiUrl应该是你的文件上传API的URL,filePath是你要上传的文件的本地路径。

相关推荐
m0_73692704几秒前
Spring Boot自动配置与“约定大于配置“机制详解
java·开发语言·后端·spring
c#上位机15 分钟前
MefBootstrapper在Prism引导程序中的使用
c#·wpf·prism
feiyangqingyun26 分钟前
Qt项目作品在苹果macos上编译运行效果/视频监控系统/物联网平台等
开发语言·qt·macos
你不是我我1 小时前
【Java 开发日记】我们来说一说 Redisson 的原理
java·开发语言
kk”1 小时前
C++ stack 和 queue
开发语言·c++
Matlab仿真实验室1 小时前
基于Matlab实现双目图计算深度图
开发语言·数码相机·matlab·双目图计算深度图
QT 小鲜肉2 小时前
【数据结构与算法基础】05. 栈详解(C++ 实战)
开发语言·数据结构·c++·笔记·学习·算法·学习方法
老K的Java兵器库2 小时前
Collections 工具类 15 个常用方法源码:sort、binarySearch、reverse、shuffle、unmodifiableXxx
java·开发语言·哈希算法
武子康2 小时前
Java-153 深入浅出 MongoDB 全面的适用场景分析与选型指南 场景应用指南
java·开发语言·数据库·mongodb·性能优化·系统架构·nosql
rit84324992 小时前
ES6 箭头函数:告别 `this` 的困扰
开发语言·javascript·es6