0

I want to upload a person's profile picture and save it in the database, and if the size is more than 200 kilobytes, it will give a warning.I saw various trainings and Lee did not help

    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PersonalCode { get; set; }
        public string NationalCode { get; set; }
        public string PhoneNumber { get; set; }
        public string MobilePhoneNumber { get; set; }
        public string EmailAddress { get; set; }
        public string Image { get; set; }
        public bool IsDeleted { get; set; }
        public bool HasAccount { get; set; }
        public User User { get; set; }
}

    [HttpPost]
    public async Task<IActionResult> UplaodProfilPicture(string Picture)
    {


        return Ok();
    }
sadegh
  • 51
  • 5

1 Answers1

0

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

enter image description here

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.

Jason Pan
  • 15,263
  • 1
  • 14
  • 29