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

相关推荐
sjtu_cjs26 分钟前
Tensorrt python api 10.11.0笔记
开发语言·笔记·python
哆啦A梦的口袋呀30 分钟前
深入理解系统:UML类图
开发语言·python·uml
虎冯河1 小时前
怎么让Comfyui导出的图像不包含工作流信息,
开发语言·python
coding随想1 小时前
JavaScript中的原始值包装类型:让基本类型也能“变身”对象
开发语言·javascript·ecmascript
2301_794333911 小时前
Maven 概述、安装、配置、仓库、私服详解
java·开发语言·jvm·开源·maven
葬爱家族小阿杰1 小时前
python执行测试用例,allure报乱码且未成功生成报告
开发语言·python·测试用例
酷爱码2 小时前
Python实现简单音频数据压缩与解压算法
开发语言·python
keepquietl2 小时前
MQTT示例体验(C)
c语言·开发语言
newxtc2 小时前
【JJ斗地主-注册安全分析报告】
开发语言·javascript·人工智能·安全