0

I have a edit form where I have to display the previously uploaded image by the user. I searched on internet and tried with the solutions but it is not working. How can I show the uploaded image and it's name?

<div class="col-md-4">
    <div class="form-group ">
        <label class="required title_header">Image</label>
        <input type="file" class="form-control" id="ImageFile" required name="ImageFile" accept="image/*">
    </div>
</div>
<div class="row">
    <div class="col-md-4">
        <div id="i_imagePrvw" class="thumbnail" style="display:none">
            <img class="img-responsive" id="i_targetImg" style="display:block; object-fit:fill;height:140px;width:120px;" />
            <div class="caption">
                <a href="#" onclick="clearPreview()"><i class="glyphicon glyphicon-trash"></i></a>
                <p id="description"></p>
            </div>
        </div>
    </div>
</div>

I am retrieving the data in json format. In console log I am getting the values as::

"ImageTitle":"98570125698.jpg",
"ImagePath":"E:\\projects\\fis\\UI\\Files\\98570125698.jpg"

I am trying to set the image name and file via this code, but it is not working.

var image_ = data.firm_model[0].ImagePath;
$('#i_targetImg').html('<img src="' + image_ + '"/>');
$('#ImageFile').val(data.firm_model[0].ImageTitle);

Showing errors as

Not allowed to load local resource: file:///E:/projects/fis/UI/Files/98570125698.jpg
Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

Please do not mark as possible duplicate, first read the whole problem. I am trying to set the image and image name but I do not know, how to do. If you have the solution, please do a reply. Thank You!

nischalinn
  • 1,133
  • 2
  • 12
  • 38
  • The **ASP.NET MVC** is designed to prevent to access local resources for security reason, in way you are trying to do. Read the following article on the Microsoft site: [Working with Files in an ASP.NET Web Pages (Razor) Site](https://learn.microsoft.com/en-us/aspnet/web-pages/overview/data/working-with-files) – Jackdaw Nov 27 '21 at 08:24

1 Answers1

1

It is very simple. Assuming that you are keeping your image (jpg) files in the folder Files inside your project. Then you can preview the uploaded image via using this code,

var image_ = "/Files/"+ data.firm_model[0].ImageTitle;
$('#i_targetImg').attr('src', image_);

You should be careful that the Files folder should be inside your root project directory. And regarding setting the name of the uploaded file in input attribute, please go through this link, How to set a value to a file input in HTML?

user4221591
  • 2,084
  • 7
  • 34
  • 68