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

相关推荐
一晌小贪欢2 分钟前
Python 对象的“Excel 之旅”:使用 openpyxl 高效读写与封装实战
开发语言·python·excel·表格·openpyxl·python办公·读取表格
赵八斤4 分钟前
java 项目中配置多个数据源
java·开发语言·数据库
txinyu的博客12 分钟前
解析muduo源码之 StringPiece.h
开发语言·网络·c++
浅念-13 分钟前
C语言——单链表
c语言·开发语言·数据结构·经验分享·笔记·算法·leetcode
2501_9445264215 分钟前
Flutter for OpenHarmony 万能游戏库App实战 - 关于页面实现
android·java·开发语言·javascript·python·flutter·游戏
Dem116 分钟前
怎么安装jdk
java·开发语言
wazmlp00188736919 分钟前
python第一次作业
开发语言·python·算法
墨雪不会编程20 分钟前
C++【string篇4】string结尾篇——字符编码表、乱码的来源及深浅拷贝
android·开发语言·c++
Engineer-Jsp26 分钟前
A problem occurred starting process ‘command ‘bash‘‘
开发语言·bash
PnZh0Y134 分钟前
python代码练习1
开发语言·python·算法