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

相关推荐
CodeCraft Studio2 小时前
Excel处理控件Aspose.Cells教程:使用 C# 在 Excel 中创建组合图表
c#·excel·aspose·图表
CodeCraft Studio2 小时前
Excel处理控件Aspose.Cells教程:使用 C# 从 Excel 进行邮件合并
开发语言·c#·excel
小超爱编程3 小时前
纯前端做图片压缩
开发语言·前端·javascript
AgilityBaby3 小时前
Unity实现不倒翁
笔记·unity·c#·游戏引擎
KIDAKN5 小时前
java--怎么定义枚举类
java·开发语言
海天胜景5 小时前
C# 中常用的 字符串截取方法
开发语言·c#
tkevinjd6 小时前
C++中线程库的基本操作
开发语言·c++
CodeWithMe7 小时前
【C/C++】不同防止头文件重复包含的措施
c语言·开发语言·c++
子豪-中国机器人7 小时前
C++ 信息学奥赛总复习题答案解析
开发语言·c++·算法
oioihoii7 小时前
C++11列表初始化:从入门到精通
java·开发语言·c++