Clients often want to store the image of users but before uploading the image of a user to the server or in a database, the client needs to allow the user to preview his/her photo.
There is very simple solution for this using JavaScript by which your page will not do a postback and the user can preview his/her photo. Let us demonstrate the preceding explanation practically by creating one simple web site as follows.
Add a new "Website" named "Website1".
And you will get the default page named "Default.aspx".
Add a File upload control named "FileUpload1" and an image control of HTML named "img" to the page.
Add a JavaScript function named "showimagepreview()" in the <script> tag as in the following:
- <script type="text/javascript">
-
- function showimagepreview(input) {
-
- if (input.files && input.files[0]) {
- var reader = new FileReader();
- reader.onload = function (e) {
-
- document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
- }
- reader.readAsDataURL(input.files[0]);
- }
- }
-
- </script>
Now I will call this function on the event named "onchange()" on the fileupload control with a parameter "this".
Note: Here the "this" parameter is the upload control itself.
- onchange="showimagepreview(this)"
Now I will run the page that will look like:
I will select the image and here is the output.