////// 使用HttpClient上传文件及传递参数 /// /// /// /// ///public static async Task HttpPostAsync(string url, NameValueCollection postParameters, List 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 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];