Add the input file tag your view.
<form asp-action="Index" asp-controller="Home">
<input type="file" id="logo" name="logo" />
<input type="submit" id="btnSave" />
</form>
We will add some javascript to listen to the submit button event and send the data via ajax.
@section Scripts
{
<script>
$(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
var fdata = new FormData();
var fileInput = $('#logo')[0];
var file = fileInput.files[0];
fdata.append("logo", file);
$.ajax({
type: 'post',
url: "@Url.Action("SaveFile","Home")",
data: fdata,
processData: false,
contentType: false,
}).done(function (result) {
// do something with the result now
console.log(result);
});
});
});
</script>
}
And you should have an an action method to accept the file posting
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public IActionResult Index(IFormFile logo)
{
if (logo != null)
{
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, GetUniqueFileName(logo.FileName));
logo.CopyTo(new FileStream(filePath, FileMode.Create));
}
// to do : Return something
return RedirectToAction("Index","Home");
}
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 file to uploads folder inside wwwwroot directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)