You need to convert your image to base64 format, then save in database.

Sample Code
1. FrontEnd Code
@{
ViewData["Title"] = "Home Page";
}
<!DOCTYPE html>
<html>
<head>
<title>Profile Picture Upload</title>
</head>
<body>
<h1>Profile Picture Upload</h1>
<form id="uploadForm">
<div>
<label for="profilePictureInput">Select Profile Picture:</label>
<input type="file" id="profilePictureInput" accept="image/*" required>
</div>
<div>
<img id="previewImage" src="#" alt="Preview" style="max-width: 300px; max-height: 300px; display: none;">
</div>
<button type="submit">Upload</button>
</form>
<script>
const fileInput = document.getElementById('profilePictureInput');
const previewImage = document.getElementById('previewImage');
fileInput.addEventListener('change', function () {
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function (e) {
previewImage.src = e.target.result;
previewImage.style.display = 'block';
}
reader.readAsDataURL(file);
});
document.getElementById('uploadForm').addEventListener('submit', function (event) {
event.preventDefault();
const file = fileInput.files[0];
var pictureSize = file.size;
if (pictureSize > 200 * 1024) {
alert("The profile picture exceeds the maximum allowed size 200k.")
return false;
}
const formData = new FormData();
formData.append('picture', file);
fetch('/Home/UplaodProfilPicture', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
console.log('Profile picture uploaded successfully');
} else {
console.error('Error uploading profile picture:', response.statusText);
}
})
.catch(error => {
console.error('Error uploading profile picture:', error);
});
});
</script>
</body>
</html>
2. Backend Code
[HttpPost]
public async Task<IActionResult> UplaodProfilPicture(IFormFile picture)
{
if (picture != null && picture.Length > 0)
{
if (picture.Length > 200 * 1024) // Check if the file size is more than 200 KB
{
// File size is too large, return a warning
return BadRequest("The profile picture exceeds the maximum allowed size.");
}
using (var memoryStream = new MemoryStream())
{
await picture.CopyToAsync(memoryStream);
var imageBytes = memoryStream.ToArray();
// Convert the image bytes to base64 string
var base64String = Convert.ToBase64String(imageBytes);
// Save the base64 string to the database
var person = new Person();
person.Image = base64String;
}
return Ok();
}
// No file was provided, return an error
return BadRequest("No profile picture file was uploaded.");
}
Tips
You can use VARCHAR(MAX)
as datatype of Image
in database.