Search code examples
asp.net-coremodelrazor-pagesbootstrap-file-input

Any Idea how to handle file input fields when updating a form


I am using asp.net core 3.1 with Razor forms. I have a form that contains an input of type file and it is multiple files input. In the create form it is easy to access the file from the model. The problem is in the update form how can handle the preview, delete adding new files to the multiple file input. Is there a best practice to solve such thing.


Solution

  • I've been using bootstrap4 file input!

    to load the images when updating the form I used the following way:

    
    var filesArray = [];
    $(document).ready(function ()
    {
        $("#photos").fileinput("refresh",
            {
                showUpload: false,
                showRemove: false
            });
        loadPhotos();
        setTimeout(function ()
        {
            if (filesArray.length > 0)
            {
                $(".file-drop-zone-title").remove();
                $('#photos').fileinput('readFiles', filesArray);
            }
        }, 2500);
       
    });
    
    function loadPhotos()
    {
        //hddPhotos is a hidden input that I stored the images URLs in
        var photosPath = $('#hddPhotos').val();
        if (photosPath !== null && photosPath!=='')
        {
            var photos = jQuery.parseJSON($('#hddPhotos').val());
            if (photos.length > 0)
            {
                var count = photos.length;
                for (var i = 0; i < count; i++)
                {
                    getBlobofImage(photos[i]);
                }
            }
        }
    }
    
    function getBlobofImage(imagePath)
    {
        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", imagePath);
        xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
        xhr.onload = function ()
        {
            blob = xhr.response;//xhr.response is now a blob object
            filesArray.push(new File([blob], /[^/]*$/.exec(imagePath)[0]));
        };
        xhr.send();
    }