HttpClient 上传文件

Posted for_oscar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient 上传文件相关的知识,希望对你有一定的参考价值。

/// <summary>
/// 发送post请求
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="pID">患者ID</param>
/// <returns></returns>
public static string HttpPostRequst(string filePath, string pID)
{
string data = string.Empty;
try
{
string url = ConfigurationManager.AppSettings["WebURLPOST"];
var fileName = Path.GetFileName(filePath);
using (var fClient = new HttpClient())
{
MultipartFormDataContent content = new MultipartFormDataContent();

FileStream fileStream = File.Open(filePath, FileMode.Open);
StreamContent streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
streamContent.Headers.ContentDisposition.Name = "ecg_file";
streamContent.Headers.ContentDisposition.FileName = fileName;
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

HttpContent strParam = new StringContent("891164e528c4450485f356d662466e5c");
strParam.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
strParam.Headers.ContentDisposition.Name = "exam_id";

content.Add(strParam);
content.Add(streamContent);

data = fClient.PostAsync(new Uri(url), content).Result.Content.ReadAsStringAsync().Result;
streamContent.Dispose();
fileStream.Dispose();

}
}
catch (Exception ex)
{
CommonLog.WriteECGLog("发送文件流出错:" + ex.Message + " " + " ", "upload");
}
return data;
}

以上是关于HttpClient 上传文件的主要内容,如果未能解决你的问题,请参考以下文章

[转]httpclient 上传文件下载文件

HttpClient:如何一次上传多个文件

Xamarin.Forms 使用HttpClient上传文件

HttpClient.PostAsync 用于上传文件

Titanium HTTPCLIENT 无法上传文件

采用HttpClient3.x上传文件 spring 文件上传