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

时间:2021-03-07 19:53:12
        /// <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];