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 "";
        }
相关推荐
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
程序猿多布8 小时前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
爬虫程序猿8 小时前
利用爬虫按关键字搜索淘宝商品实战指南
android·爬虫
顾北川_野8 小时前
Android ttyS2无法打开该如何配置 + ttyS0和ttyS1可以
android·fpga开发
阿蒙Amon9 小时前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#
开开心心_Every9 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text
Kookoos11 小时前
ABP VNext + .NET Minimal API:极简微服务快速开发
后端·微服务·架构·.net·abp vnext
深盾科技11 小时前
.NET 安全之 JIT 保护技术深度解析
安全·.net
wzj_what_why_how11 小时前
Android网络层架构:统一错误处理的问题分析到解决方案与设计实现
android·架构