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

相关推荐
小无名呀19 分钟前
C++初阶:类和对象(上)
开发语言·c++
杰克逊的日记24 分钟前
JAVA8引入了哪些新特性
java·开发语言·jdk8
Dylanioucn25 分钟前
【编程底层原理】Java双亲委派模型
java·开发语言·后端
nihui12326 分钟前
Java面试篇基础部分-Java序列化
java·开发语言·面试
胶水给你吃28 分钟前
@Valid @NotBlank @NotEmpty @NotNull不生效问题
java·开发语言
Energet!c29 分钟前
1分钟解决 -bash: mvn: command not found,在Centos 7中安装Maven
开发语言
Nonullpoint.40 分钟前
《深入理解 Java 中的多线程基础(篇一)》
java·开发语言·线程
LilKevinRay1 小时前
【JAVA基础】实现Tomcat基本功能
java·开发语言·笔记·tomcat
湫兮之风1 小时前
C++:opencv计算轮廓周长--cv::arcLength
开发语言·c++·opencv
ya888g2 小时前
C++ STL 数据结构 vector基本用法
开发语言·数据结构·c++