Reputation: 543
I am trying to upload file using HttpClient in Asp.net Core 3, but It is not uploading file to the server. If I try to upload file to the server via Postman, it works.
Below is my simple code to upload file:
HttpClient _client = new HttpClient();
var stream = new FileStream("main.txt", FileMode.Open);
byte[] fileBytes = new byte[stream.Length];
stream.Write(fileBytes, 0, (int)stream.Length);
stream.Dispose();
using (var content = new MultipartFormDataContent())
{
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Test",
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
content.Add(fileContent);
_client.PostAsync("http://192.168.56.1:8000", content);
}
As I said above it is working with Postman. I am putting a screenshot which shows that how I doing with Postman.
when I debug the code, so I get below error.
Upvotes: 3
Views: 6246
Reputation: 851
I've downloaded the server and tested it with this code. The server returns 200 OK
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
using (var fileStream = new FileStream("test.txt", FileMode.Open))
{
var fileContent = new StreamContent(fileStream);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
content.Add(fileContent, "file", "test.txt");
var response = await client.PostAsync("http://192.168.56.1:8000/", content);
}
}
}
Upvotes: 0
Reputation: 20116
One solution is that you could use MemoryStream
to transform the content of the file. Your method will cause the content in the main.txt file to become empty.
Change your code like this:
HttpClient _client = new HttpClient();
Stream stream = new FileStream("main.txt", FileMode.Open);
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
byte[] fileBytes = ms.ToArray();
ms.Dispose();
Another way is that use System.IO.File.ReadAllBytes(filePath)
.
Try to post file using below example code instead, refer to my answer.
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
//replace with your own file path, below use an txt in wwwroot for example
string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "main.txt");
byte[] file = System.IO.File.ReadAllBytes(filePath);
var byteArrayContent = new ByteArrayContent(file);
content.Add(byteArrayContent, "file", "main.txt");
var url = "https://localhost:5001/foo/bar";
var result = await client.PostAsync(url, content);
}
}
foo/bar action
[HttpPost]
[Route("foo/bar")]
public IActionResult ProcessData([FromForm]IFormFile file)
{
//your logic to upload file
}
Upvotes: 1