HTTPClient以WebAPI方式傳送formData資料上傳檔案
阿新 • • 發佈:2020-11-27
Net以WebAPI形式傳送fromData格式的資料上傳檔案,示例程式碼如下:
public static async Task<HttpResponseMessage> HttpPostFileAsync(string url, BearerToken token, BillReconcileFileTenant billReconcile, string filePath) { using (var httpClient = new HttpClient() { BaseAddress = new Uri(baseAddress) }) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Authorization= new AuthenticationHeaderValue("Bearer", token.access_token); using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { MultipartFormDataContent formData = new MultipartFormDataContent(); formData.Add(new StringContent(billReconcile.TenantName), "\"TenantName\"");// 使用"\"來轉義 formData.Add(new StringContent(billReconcile.BillDate), "\"BillDate\""); formData.Add(new StringContent(billReconcile.Count.ToString()), "\"Count\""); formData.Add(newStringContent(billReconcile.Amount.ToString()), "\"Amount\""); formData.Add(new StreamContent(fileStream, (Int32)fileStream.Length), "Data", billReconcile.FileName); HttpResponseMessage response = await httpClient.PostAsync(url, formData); if (!response.IsSuccessStatusCode) { LogUtil.Error($"{DateTime.Now.ToString()}對賬介面對賬失敗,返回狀態碼為:{Convert.ToInt32(response.StatusCode)}"); } else { LogUtil.Info($"{DateTime.Now.ToString()}對賬介面Post請求成功,返回狀態碼為:{Convert.ToInt32(response.StatusCode)}"); } return response; } } }
注意:BaseAddress和url使用時是BaseAddress+url為請求地址再去使用。