C# HttpClient Post參數(shù)同時上傳文件的實現(xiàn)
更新時間:2022年06月09日 09:36:38 作者:luofeng0710
這篇文章主要介紹了C# HttpClient Post參數(shù)同時上傳文件的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
HttpClient Post參數(shù)同時上傳文件
Demo 如下
using (var client = new HttpClient())
{
? ? using (var multipartFormDataContent = new MultipartFormDataContent())
? ? {
? ? ? ? var values = new[]
? ? ? ? {
? ? ? ? ? ? new KeyValuePair<string, string>("c", "3"),
? ? ? ? ? ? new KeyValuePair<string, string>("c", "2"),
? ? ? ? ? ? new KeyValuePair<string, string>("d", "2")
? ? ? ? ? ? ?//other values
? ? ? ? };
?
? ? ? ? foreach (var keyValuePair in values)
? ? ? ? {
? ? ? ? ? ? multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
? ? ? ? ? ? ? ? String.Format("\"{0}\"", keyValuePair.Key));
? ? ? ? }
?
? ? ? ? multipartFormDataContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(@"D:\test.jpg")),
? ? ? ? ? ? "\"pic\"",
? ? ? ? ? ? "\"test.jpg\"");
?
? ? ? ? var requestUri = "http://localhost:8080";
? ? ? ? var html = client.PostAsync(requestUri, multipartFormDataContent).Result.Content.ReadAsStringAsync().Result;
? ? }
}HttpClient上傳文件到服務(wù)器(multipart/form-data)
string reqUrl = JsonrpcHttpClient.MakeRpcUrl(typeof(Wfm_SimReport).Name, "save");
using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))//若想手動設(shè)置Cookie則必須設(shè)置UseCookies = false
{
string boundary = string.Format("----WebKitFormBoundary{0}",DateTime.Now.Ticks.ToString("x"));
MultipartFormDataContent content = new MultipartFormDataContent(boundary);
#region 設(shè)置請求參數(shù)
content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
content.Headers.Add("Cookie", TokenManager.Token);
content.Headers.Add("client", "true");
#endregion
if (string.IsNullOrEmpty(fullPath) && !File.Exists(fullPath))
{
return false;
}
string fileName = Path.GetFileName(fullPath);
#region Stream請求
FileStream fStream = File.Open(fullPath, FileMode.Open, FileAccess.Read);
content.Add(new StreamContent(fStream, (int)fStream.Length), "file", fileName);
#endregion
content.Add(new StringContent(JsonHelper.Serialize(entity)), "dtoStr");
var result = client.PostAsync(reqUrl, content).Result;
try
{
if (result.IsSuccessStatusCode)
{
string rslt = result.Content.ReadAsStringAsync().Result;
Debug.WriteLine(rslt);
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("獲取服務(wù)器返回結(jié)果錯誤:消息:{0},堆棧:{1}",ex.Message,ex.StackTrace));
}
finally
{
//關(guān)閉文件流
fStream.Close();
client.Dispose();
}
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#中將DataTable轉(zhuǎn)換成CSV文件的方法
DataTable用于在.net項目中,用于緩存數(shù)據(jù),DataTable表示內(nèi)存中數(shù)據(jù)的一個表,在.net項目中運用C#將DataTable轉(zhuǎn)化為CSV文件,接下來通過本文給大家提供一個通用的方法,感興趣的朋友可以參考下2016-10-10
C#基于Socket的網(wǎng)絡(luò)通信類你了解嗎
這篇文章主要為大家詳細介紹了C#基于Socket的網(wǎng)絡(luò)通信類,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03

