[英]How to solve HttpRequestException while calling HttpClient PostAsync method to upload image
[英]How to upload a file and a parameter to a remote server via HttpClient PostAsync method?
我正在尝试将文件从我的桌面应用程序上传到远程服务器。 在浏览了一段时间之后,这种方法似乎是最干净的方法。 问题是在服务器端都没有收到参数。 我错过了什么?
private void AddFile(FileInfo fileInfo, int folderId)
{
using (var handler = new HttpClientHandler() {CookieContainer = _cookies})
{
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.Open(FileMode.Open));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent, "file", "file");
requestContent.Add(folderContent, "folderId", "folderId");
client.PostAsync("/Company/AddFile", requestContent);
}
}
}
编辑:这是服务器端期望的签名:
[HttpPost]
public ActionResult AddFile(HttpPostedFileBase file, int folderId)
经过大量的反复试验,我得到了它。 有一些问题。 1)引号中的参数名称预期2)我遗漏了一堆标题信息。 这是工作代码。
private void AddFile(FileInfo fileInfo, int folderId)
{
using (var handler = new HttpClientHandler() {CookieContainer = _cookies})
{
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.OpenRead());
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = "\"file\"",
FileName = "\"" + fileInfo.Name + "\""
};
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent);
requestContent.Add(folderContent, "\"folderId\"");
var result = client.PostAsync("Company/AddFile", requestContent).Result;
}
}
在客户端: using(var formData = new MultipartFormDataContent()){formData.Add(new StreamContent(new MemoryStream(bytes)),“file”,Model.BaseFileName); string result = client.PostAsync(“ https://fakeurl.com/Controller/Action?inputParams= ”+ Params,formData).Result.Content.ReadAsStringAsync()。Result;}
在服务器端: var httpRequest = System.Web.HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
//foreach (string file in httpRequest.Files)
//{
HttpPostedFile postedFile = httpRequest.Files[0];
// Initialize the stream.
Stream mstream = postedFile.InputStream;
byte[] byteArray = new byte[postedFile.ContentLength];
postedFile.InputStream.Read(byteArray, 0, postedFile.ContentLength);
本文提出一个完整的解决方案:https ://makolyte.com/csharp-how-to-send-a-file-with-httpclient/
上传单个文件的代码:
var filePath = @"C:\house.png";
using (var multipartFormContent = new MultipartFormDataContent())
{
//Load the file and set the file's Content-Type header
var fileStreamContent = new StreamContent(File.OpenRead(filePath));
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
//Add the file
multipartFormContent.Add(fileStreamContent, name: "file", fileName: "house.png");
//Send it
var response = await httpClient.PostAsync("https://localhost:12345/files/", multipartFormContent);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
上传文件和一些表单字段的代码:
var filePath = @"C:\house.png";
using (var multipartFormContent = new MultipartFormDataContent())
{
//Add other fields
multipartFormContent.Add(new StringContent("123"), name: "UserId");
multipartFormContent.Add(new StringContent("Home insurance"), name: "Title");
//Add the file
var fileStreamContent = new StreamContent(File.OpenRead(filePath));
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
multipartFormContent.Add(fileStreamContent, name: "file", fileName: "house.png");
//Send it
var response = await httpClient.PostAsync("https://localhost:12345/files/", multipartFormContent);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.