var file = Request.Form.Files.FirstOrDefault();
var LogoUrl = _webHostEnvironment.UploadFile(file);
public static string UploadFile(this IWebHostEnvironment _webHostEnvironment, IFormFile? file, string uploadPath= "/AdminTemplate/Images/")
{
if (file == null || uploadPath == null)
return string.Empty;
if (uploadPath.Length > 0 && uploadPath[0] != '/')
throw new ArgumentException("file path must start wit /");
try
{
var fileName = DateTime.Now.ToString("hhmmss") + file.FileName;
var imgDirectory = Path.Combine(_webHostEnvironment.WebRootPath, uploadPath[1..].Replace("/", "\\"));
if (!Directory.Exists(imgDirectory))
Directory.CreateDirectory(imgDirectory);
var filePath = Path.Combine(imgDirectory, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(stream);
}
var absoluteFilePath = uploadPath + fileName;
return absoluteFilePath;
}
catch (Exception)
{
throw;
}
}
<div class="d-flex align-items-start align-items-sm-center gap-4">
<img src="../assets/img/avatars/1.png"
alt="user-avatar"
class="d-block rounded"
height="100"
width="100"
id="uploadedAvatar" />
<div class="button-wrapper">
<label for="upload" class="btn btn-primary me-2 mb-4" tabindex="0">
<span class="d-none d-sm-block">Upload new photo</span>
<i class="bx bx-upload d-block d-sm-none"></i>
<input type="file"
id="upload"
class="account-file-input"
hidden
accept="image/png, image/jpeg" />
</label>
<button type="button" class="btn btn-outline-secondary account-image-reset mb-4">
<i class="bx bx-reset d-block d-sm-none"></i>
<span class="d-none d-sm-block">Reset</span>
</button>
<p class="text-muted mb-0">Allowed JPG, GIF or PNG. Max size of 800K</p>
</div>
</div>
document.addEventListener('DOMContentLoaded', function (e) {
(function () {
let accountUserImage = document.getElementById('uploadedAvatar');
const fileInput = document.querySelector('.account-file-input'),
resetFileInput = document.querySelector('.account-image-reset');
if (accountUserImage) {
const resetImage = accountUserImage.src;
fileInput.onchange = () => {
if (fileInput.files[0]) {
accountUserImage.src = window.URL.createObjectURL(fileInput.files[0]);
}
};
resetFileInput.onclick = () => {
fileInput.value = '';
accountUserImage.src = resetImage;
};
}
})();
});