C#.NET使用multipart/form-data方式上传文件及其他数据

server/2024/12/19 8:29:51/

在这里插入图片描述

请求发起

.NET Framework 3.5 版

/// <summary>/// 使用multipart/form-data方式上传文件及其他数据/// </summary>/// <param name="headers">请求头参数</param>/// <param name="nameValueCollection">键值对参数</param>/// <param name="fileCollection">文件参数:参数名,文件路径</param>/// <returns>接口返回结果</returns>public static string PostMultipartFormData(string url, Dictionary<string, string> headers, NameValueCollection nameValueCollection, NameValueCollection fileCollection){using (var client = new HttpClient()){foreach (var item in headers){client.DefaultRequestHeaders.Add(item.Key, item.Value);}using (var content = new MultipartFormDataContent()){// 键值对参数string[] allKeys = nameValueCollection.AllKeys;foreach (string key in allKeys){var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"){Name = key};content.Add(dataContent);}//处理文件内容string[] fileKeys = fileCollection.AllKeys;foreach (string key in fileKeys){byte[] bmpBytes = File.ReadAllBytes(fileCollection[key]);var fileContent = new ByteArrayContent(bmpBytes);//填充文件字节fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"){Name = key,FileName = Path.GetFileName(fileCollection[key])};content.Add(fileContent);}var result = client.PostAsync(url, content).Result;//post请求string data = result.Content.ReadAsStringAsync().Result;return data;//返回操作结果}}}

.NET Framework 4.+ 版

/// <summary>/// 使用multipart/form-data方式上传文件及其他数据/// </summary>/// <param name="headers">请求头参数</param>/// <param name="nameValueCollection">键值对参数</param>/// <param name="fileCollection">文件参数:参数名,文件路径</param>/// <returns>接口返回结果</returns>public static string PostMultipartFormData(string url, Dictionary<string, string> headers, NameValueCollection nameValueCollection, NameValueCollection fileCollection){using (var client = new HttpClient()){foreach (var item in headers){client.DefaultRequestHeaders.Add(item.Key, item.Value);}using (var content = new MultipartFormDataContent()){// 键值对参数string[] allKeys = nameValueCollection.AllKeys;foreach (string key in allKeys){var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"){Name = key};content.Add(dataContent);}//处理文件内容string[] fileKeys = fileCollection.AllKeys;foreach (string key in fileKeys){byte[] bmpBytes = File.ReadAllBytes(fileCollection[key]);var fileContent = new ByteArrayContent(bmpBytes);//填充文件字节fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"){Name = key,FileName = Path.GetFileName(fileCollection[key])};content.Add(fileContent);}var result = client.PostAsync(url, content).Result;//post请求string data = result.Content.ReadAsStringAsync().Result;return data;//返回操作结果}}}

Web API 接收接口
ASP .NET Core Web API 接口接收 multipart/form-data 文件、数据

[HttpPost]//public string Post([FromForm] string directory, [FromForm] IList<IFormFile> files )public string Post([FromForm] string directory, [FromForm] IFormFile files){return "";}[HttpPut]public string Put([FromForm] IFormFile templateFile, [FromForm] string id, [FromForm] string objectVersionNumber){return "";}

ASP.NET 4.x 版

[HttpPost(Name = "PostWeatherForecast")]//public string Post([FromForm] string directory, [FromForm] IList<IFormFile> files )public string Post([FromForm] string directory, [FromForm] IFormFile files){// Check if the request contains multipart/form-data.if (!Request.ContentType.IsMimeMultipartContent()){throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);}string root = Request.HttpContext.Current.Server.MapPath("~/App_Data");var provider = new MultipartFormDataStreamProvider(root);try{// Read the form data.await Request.Content.ReadAsMultipartAsync(provider);// This illustrates how to get the file names.//foreach (MultipartFileData file in provider.FileData)//{//    Trace.WriteLine(file.Headers.ContentDisposition.FileName);//    Trace.WriteLine("Server file path: " + file.LocalFileName);//}//  return Request.CreateResponse(HttpStatusCode.OK);}catch (System.Exception e){//  return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);}return "";}

http://www.ppmy.cn/server/151397.html

相关文章

moment()获取时间

moment 是一个 JavaScript 日期处理类库。 使用&#xff1a; //安装 moment npm install moment -- save引用 //在main.js中全局引入 import moment from "moment"设定moment区域为中国 //import 方式 import moment/locale/zh-cn moment.locale(zh-cn); 挂载全…

上传文件(vue3)

使用el-upload 先上传到文件服务器&#xff0c;生成url 然后点击确定按钮&#xff1a; 保存数据 <template><el-dialog top"48px" width"500" title"新增协议" :modelValue"visible" close"handleClose()">…

Group FLUX - User Usage Survey Report

文章目录 User Feedback Summary: Software Advantages and FeaturesUser Feedback Issues and Suggested Improvements1. Security Concerns:Improvement Measures: 2. System Performance and Loading Speed:Improvement Measures: 3. Data Display Issues:Improvement Measu…

随手记:小程序兼容后台的wangEditor富文本配置链接

场景&#xff1a; 在后台配置wangEditor富文本&#xff0c;可以文字配置链接&#xff0c;图片配置链接&#xff0c;产生的json格式为&#xff1a; 例子&#xff1a; <h1><a href"https://uniapp.dcloud.net.cn/" target"_blank"><span sty…

RadiAnt DICOM - 基本主题 :从 PACS 服务器打开研究

正版序列号获取&#xff1a;https://r-g.io/42ZopE RadiAnt DICOM Viewer PACS 客户端功能允许您从 PACS 主机&#xff08;图片存档和通信系统&#xff09;搜索和下载研究。 在开始之前&#xff0c;您需要确保您的 PACS 服务器和 RadiAnt 已正确配置。有关配置说明&#xff0c…

Vite系列课程 | 6. Vite 的依赖预加载和预构建,7. Vite 配置文件处理细节

6. Vite 的依赖预加载和预构建 Vite 能够显著提升开发体验的关键特性之一就是其依赖预加载和预构建机制。 6.1 依赖预加载与路径处理 当我们使用 ES 模块导入依赖时&#xff0c;例如&#xff1a; import Vue from vue; import someModule from ./some-module.js;Vite 在构建…

docker 拉取镜像 | 创建容器 | 容器运行

拉取镜像 拉取镜像的命令&#xff1a;docker pull name &#xff08;name换为你要拉取的镜像名&#xff09; docker pull docker.1panel.live/hispark/qiankunbp:1.0.0 docker.1panel.live/hispark/qiankunbp:1.0.0为镜像名 拉取海思的镜像&#xff1a;&#xff08;如果之前拉…

Spring Framework 路径遍历漏洞复现(CVE-2024-38819)

hu0x01 产品描述: Spring Framework 是一个功能强大的 Java 应用程序框架,旨在提供高效且可扩展的开发环境。它结合了轻量级的容器和依赖注入功能,提供了一种使用 POJO 进行容器配置和面向切面的编程的简单方法,以及一组用于AOP的模块。0x02 漏洞描述: Spring Framework 存…