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

请求发起

.NET Framework 3.5 版

csharp 复制代码
/// <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.+ 版

csharp 复制代码
/// <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 文件、数据

csharp 复制代码
[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 版

csharp 复制代码
[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 "";
        }
相关推荐
喵叔哟27 分钟前
24.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--单体转微服务--认证微服务
微服务·架构·.net
xzkyd outpaper27 分钟前
onSaveInstanceState() 和 ViewModel 在数据保存能力差异
android·计算机八股
CYRUS STUDIO2 小时前
FART 脱壳某大厂 App + CodeItem 修复 dex + 反编译还原源码
android·安全·逆向·app加固·fart·脱壳
Java Fans2 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
WAsbry2 小时前
现代 Android 开发自定义主题实战指南
android·kotlin·material design
IGP92 小时前
20250606-C#知识:委托和事件
开发语言·c#
xzkyd outpaper2 小时前
Android动态广播注册收发原理
android·计算机八股
唐墨1233 小时前
android与Qt类比
android·开发语言·qt
书中自有妍如玉3 小时前
.net 使用MQTT订阅消息
java·前端·.net
Kookoos3 小时前
ABP VNext 与 Neo4j:构建基于图数据库的高效关系查询
数据库·c#·.net·neo4j·abp vnext