I'm attempting to upload a file from my desktop application to a remote server. After browsing SO for a while this approach seems to be the cleanest way to go about it. The problem is neither parameter is received at the server side. What am I missing?
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);
}
}
}
edit: This is the signature the server side is expecting:
[HttpPost]
public ActionResult AddFile(HttpPostedFileBase file, int folderId)
After a lot of trial and error I got it. There were a few problems. 1) paramater names are expected in quotes 2) I was missing a bunch of header information. Here's the working code.
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;
}
}
At client end: 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;}
At Server End: 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);
This article propose a complete solution:https://makolyte.com/csharp-how-to-send-a-file-with-httpclient/
Code to upload a single file:
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();
}
Code to upload a file and some form fields:
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.