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

相关推荐
匠心网络科技9 分钟前
JavaScript进阶-ES6 带来的高效编程新体验
开发语言·前端·javascript·学习·面试
一只大袋鼠25 分钟前
并发编程(三):线程快照统计・grep+awk+sort+uniq 实战详解
java·开发语言·多线程·并发编程
Hx_Ma1641 分钟前
前台模块以及分页逻辑
java·开发语言
亓才孓1 小时前
AspectJ和SpringAOP的区别
java·开发语言
大鹏说大话1 小时前
破局单体瓶颈:SQLParser 解析器的分层架构重构实战
开发语言
tod1131 小时前
C++ 核心知识点全解析(八)
开发语言·c++·面试经验
Ljwuhe1 小时前
C++类与对象(上)
开发语言·c++
十启树1 小时前
QGis开发环境部署
开发语言·gis·qgis
亚比囧1 小时前
Java基础--面向对象(二)
java·开发语言
乐观勇敢坚强的老彭1 小时前
c++寒假营day05
开发语言·c++·算法