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

相关推荐
全职计算机毕业设计8 分钟前
基于Java Web的校园失物招领平台设计与实现
java·开发语言·前端
5:0027 分钟前
云备份项目
linux·开发语言·c++
笨笨马甲1 小时前
Qt Quick模块功能及架构
开发语言·qt
夜晚回家1 小时前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS3141 小时前
C++动态规划-01背包
开发语言·c++·动态规划
安木夕1 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
前端页面仔2 小时前
易语言是什么?易语言能做什么?
开发语言·安全
树叶@2 小时前
Python数据分析7
开发语言·python
wydaicls2 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地2 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药