使用HttpClient上传文件及传递参数


        /// <summary>
        /// 使用HttpClient上传文件及传递参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postParameters"></param>
        /// <param name="lstFilePath"></param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, NameValueCollection postParameters, List<string> lstFilePath = null)
        {
            //var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            
            using (var httpClient = new HttpClient())
            {
                using (MultipartFormDataContent formData = new MultipartFormDataContent()) 
                {                    
                    if (lstFilePath != null)
                    {
                        for (int i = 0; i < lstFilePath.Count; i++)
                        {
                            int start = lstFilePath[i].LastIndexOf('\\');
                            string name = lstFilePath[i].Substring(start + 1);
                            var fileContent = new ByteArrayContent(File.ReadAllBytes(lstFilePath[i]));
                            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                            {
                                FileName = name
                            };
                            formData.Add(fileContent);
                        }                       
                    }
                    foreach (string key in postParameters.Keys)
                    {
                        formData.Add(new StringContent(postParameters[key]), key);
                    }
                    
                    Task<HttpResponseMessage> response = httpClient.PostAsync(url, formData);
                    string tempResult = await response.Result.Content.ReadAsStringAsync();
                    return tempResult;
                }               
            }
        }

后端接受 

NameValueCollection request = context.Request.Params;
HttpPostedFile file = context.Request.Files[0];


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM