ASP.NET MVC image upload form with image preview

This document shows how to code an image upload form with image preview.

 

This document was most recently updated in November 2015.

 

Scenario

HTML Form, to enable a user to upload an image.

With an input type=file element.

 

Objective

After the user selects a file, it would be nice if the image was previewed, before it was uploaded. For example:

input-file-preview-image

 

Here’s how to implement this behaviour. We need to use JavaScript.

 

Configure the input element

The important attribute in the input element is “onchange”. It specifies the name of the JavaScript function that runs when the value or state of the element changes.

<div class="form-group">
    @Html.Label("Photo", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <input type="file" name="PhotoUpload" class="form-control" 
            accept="image/*" 
            onchange="previewImage(event)" />
    </div>
</div>

 

Configure the img element

The important attribute in the img element is “id”. The JavaScript function will select this element using its value.

<div class="form-group">
    @Html.Label("Existing photo (if any)", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <img src='@("/instruments/details/" + Model.Id + "/photo")' 
            alt="" id="instrumentImage" 
            class="img-thumbnail" width="280" />
    </div>
</div>

 

Write the JavaScript function

The input element has a files property, which is a collection.

The function reads the one-and-only value in that collection, constructs a URL, and sets it to the value of the image’s src attribute.

function previewImage(event) {
    // Get a reference to the image element
    var image = document.querySelector("#instrumentImage");
    // Set its source to the file in the <input type=file element
    image.src = URL.createObjectURL(event.target.files[0]);
};

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

 

Advertisements
%d bloggers like this: