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

相关推荐
共享家95272 小时前
Qt 实战-Music 播放器
开发语言·qt
上不如老下不如小2 小时前
2025年第七届全国高校计算机能力挑战赛 决赛 Python组 编程题汇总
开发语言·python
老华带你飞2 小时前
校园快递|基于Java校园快递管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
smile_Iris3 小时前
Day 32 类的定义和方法
开发语言·python
AndreasEmil3 小时前
JavaSE - 继承
java·开发语言·ide·vscode·intellij-idea·idea
老华带你飞9 小时前
博物馆展览门户|基于Java博物馆展览门户系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
liulilittle9 小时前
FileStream C++
开发语言·c++·cocoa
yue0089 小时前
C# 实现日志记录功能
c#·日志记录
点PY9 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
不会代码的小猴9 小时前
C++的第九天笔记
开发语言·c++·笔记