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是你要上传的文件的本地路径。

相关推荐
宋情写2 分钟前
Java基础篇01-环境搭建+入门体验
java·开发语言
cike_y6 分钟前
Mybatis-万能的Map&模糊查询
java·开发语言·mybatis·安全开发
郝学胜-神的一滴11 分钟前
Linux的pthread_self函数详解:多线程编程中的身份标识器
linux·运维·服务器·开发语言·c++·程序人生
HUST16 分钟前
C 语言 第七讲:数组和函数实践:扫雷游戏
c语言·开发语言·数据结构·vscode·算法·游戏·c#
oioihoii16 分钟前
C++高并发编程核心技能解析
开发语言·c++
jimy121 分钟前
程序崩溃free(): double free detected in tcache 2
linux·开发语言·数据结构·链表
秋邱25 分钟前
Java面向对象进阶:封装、继承、多态的实现逻辑与实战案例
java·开发语言·后端·spring cloud·ar·restful
colman wang31 分钟前
Java期末
java·开发语言
千里马-horse32 分钟前
AsyncContext
开发语言·前端·javascript·c++·napi·asynccontext