i am new to ASP.net COre and i would like to upload a file ( an image) and store it in a secific Folder. ihave been following this tuto (File uploads in ASP.NET Core) but i
You should inject IHostingEnvironment
so you can get the web root (wwwroot
by default) location.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public async Task UploadFiles(List files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "images");
var fullPath = Path.Combine(uploads, GetUniqueFileName(formFile.FileName));
formFile.CopyTo(new FileStream(fullPath, FileMode.Create));
}
return Ok(new { count = files.Count, size, filePath });
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
This will save the files to the images
directory in wwwroot
.
Make sure that your form tag's action
attribute is set to the UploadFiles
action method of HomeController(/Home/UploadFiles
)
I am not very certain why you want to return Ok result from this. You may probably return a redirect result to the listing page.