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

相关推荐
大锦终5 分钟前
【C++】unordered_map与set的模拟实现
开发语言·数据结构·c++·哈希算法
范纹杉想快点毕业19 分钟前
以项目的方式学QT开发C++(二)——超详细讲解(120000多字详细讲解,涵盖qt大量知识)逐步更新!
c语言·开发语言·c++·windows·vscode·qt·visual studio
多多*33 分钟前
Spring之Bean的初始化 Bean的生命周期 全站式解析
java·开发语言·前端·数据库·后端·spring·servlet
少了一只鹅1 小时前
c语言内存函数
c语言·开发语言
じ☆ve 清风°1 小时前
滑动窗口算法详解与C++实现
开发语言·c++·算法
苕皮蓝牙土豆1 小时前
C++ map & multimap 容器:赋值、排序、大小与删除操作
开发语言·c++
Villiam_AY1 小时前
Go 后端中双 token 的实现模板
开发语言·后端·golang
DjangoJason1 小时前
计算机网络 : Socket编程
linux·服务器·开发语言·笔记·计算机网络
映秀小子1 小时前
C语言链表的操作
c语言·开发语言·链表