0

I am working on a project in which I have to make a CV builder. I am using the same form to edit and insert. Edit returns the same Index method but with the particular information about that Id.
My issue is that I don't know how to bind that particular image in input type=" file" and I always run into the condition of "Please Choose an Image".
All the images are saved in the Images folder that I've created in the project.

Screen shots When I am browsing and choosing an Image When I return View with specific information about that Id

Razor View

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data", id = "quickForm" }))
        {
           <div class="col-md-4">
                    <!-- Image Upload -->
                    <div class="container">
                        <div class="avatar-upload">
                            <div class="avatar-edit">
                                <input type='file' name="File" id="File" src="@(Model.ImagePath != null && File.Exists(Server.MapPath(Model.ImagePath)) ? Server.MapPath(Model.ImagePath) : Url.Content("~/Content/Images/Default_Image.png" ))" accept=".png, .jpg, .jpeg" required />
                                <label for="File"></label>
                            </div>
                            <div class="avatar-preview" style="width:100%;height:13em">
                                <div id="imagePreview" style="background-image: url('@(Model.ImagePath != null && File.Exists(Server.MapPath(Model.ImagePath)) ? Url.Content(Model.ImagePath) : Url.Content("~/Content/Images/Default_Image.png" ))');">
                                    @*../../Content/Images/Default_Image.png*@
                                </div>
                            </div>
                        </div>
                        <h1>
                             Image Upload
                            <small>.png, .jpg, .jpeg</small>
                        </h1>
                    </div>
                </div>
        }

I am setting the source of File through JQuery

        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#imagePreview').css('background-image', 'url(' + e.target.result + ')');
                    $('#imagePreview').hide();
                    $('#imagePreview').fadeIn(650);
                    $('#File').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        $("#File").change(function () {
            readURL(this);
        });

Model Class

 public class BasicInformation
    {
        [Required]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [StringLength(150)]
        public string ImageTitle { get; set; }
        [StringLength(150)]
        public string ImagePath { get; set; }
        [NotMapped]
        public HttpPostedFileBase File { get; set; }
    }

Controller Method

public ActionResult Index(int? id)
        {
            BasicInformation info = db.BasicInformation.Find(id);
            if (info != null)
            {
                return View(info);
            }
            else
            {
                BasicInformation information = new BasicInformation();
                return View(information);
            }
        }

2 Answers2

0

Unluckly no, you can't change the value of an input type="file" because of security restriction.

Look here.

I had the same issue; I was creating a form that worked as creation and editing for the same data. The only way to do that is submiting the request without a file and in backend check if file exists in post request. If it exists, replace that in database/disk, if not, keep the old one.

But how do the user understand if a file exists or not? The only way is to place something that indicates the current file.

For images usually I place an <img> beside the and I fill img with existing img from database.

Then, if you want to make it even better, you can listen for onChange of <input type="file" and if the file is an image you can please it as src into the so user will have a real time preview of that image.

For example, look this

  • I am previewing the image using jQuery. Btw Thanks for your feedback. Really unlucky for me though because in the frontend, I am validating the form using JQuery and sending an ajax request afterward. Ajax request is not sent if the file doesn't exist. Unluckily for me, I have to refactor my code now I guess. – Muhammad Qasim Aug 13 '21 at 16:25
0

You can try to create a blob from the src1 attribute, then create a File object. Create a Clipboad object to get access to a FileList, then add the file to the file list and replace the file list on the input with the one from the clipboard

// show the file in the input field
$('#File').on('change', function(){
    var url = URL.createObjectURL(this.files[0]);
    $('#Image').prop('src', url);
});
var url = $('#File').attr('src');
fetch(url)
.then(res => res.blob())
.then(blob =>{
    const dt = new ClipboardEvent('').clipboardData || new DataTransfer(); 
    dt.items.add(new File([blob], 'some_file_name.ext'));
    $('#File').prop('files', dt.files);
    $('#File').trigger('change');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' name="File" id="File" src="data:image/png;base64,iVBORw0KGgoAAA
ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
5ErkJggg==" accept=".png, .jpg, .jpeg" required />
<img id="Image">
  1. I would suggest using data-src as the attribute instead.
Musa
  • 96,336
  • 17
  • 118
  • 137