C
C#2mo ago
AideedSS

How to make upload file in ASP.NET Core?

any tutorial on how to make upload file in ASP.NET Core...via html, javascript, c# (backend code)..
6 Replies
Sossenbinder
Sossenbinder2mo ago
There's an entire MSDN article on this IFormFile is probably the easiest way to do it
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2mo ago
In case you did not read the docs: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0 Client Code:
private readonly HttpClient _httpClient;

private static async Task UploadSampleFileAsync()
{
await using var stream = File.OpenRead("./Test.txt");
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/whatever/upload");
using var content = new MultipartFormDataContent
{
{ new StreamContent(stream), "file", "Test.txt" }
};

request.Content = content;

await client.SendAsync(request);
}
private readonly HttpClient _httpClient;

private static async Task UploadSampleFileAsync()
{
await using var stream = File.OpenRead("./Test.txt");
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/whatever/upload");
using var content = new MultipartFormDataContent
{
{ new StreamContent(stream), "file", "Test.txt" }
};

request.Content = content;

await client.SendAsync(request);
}
ServerCode:
[ApiController]
[Route("api/whatever")]
public class FileController : ControllerBase
{
[HttpPost("upload")]
public IActionResult Upload([FromForm] IFormFile file)
{
// code responsible for file processing
return Ok();
}
}
[ApiController]
[Route("api/whatever")]
public class FileController : ControllerBase
{
[HttpPost("upload")]
public IActionResult Upload([FromForm] IFormFile file)
{
// code responsible for file processing
return Ok();
}
}
The field's name in the body when doing the POST, needs to match the binded field in the Controler's Action https://media.discordapp.net/attachments/569261465463160900/1001188081069735936/unknown.png
Upload files in ASP.NET Core
How to use model binding and streaming to upload files in ASP.NET Core MVC.
Sossenbinder
Sossenbinder2mo ago
TIL there's a tag for this, this must be a super regular question lol
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server