Display Image Using Upload Js
Solution 1:
The browser does NOT allow javascript full access to the .value
property of an input tag with type="file"
. This is for security reasons so no local path information is made available to javascript.
Thus, you can't set a .src
value on an image tag based on a file input value that the end-user specified.
Solution 2:
If you don't want to upload the image to server side, you have a possibility to do it only in the client side.
add a div to your html (dom):
<div id='bottom'>
<div id='drag-image' class='holder-file-uploader bottom-asset'> Drag here an image</div>
</div>
add this javascript:
<script>var holder = document.getElementById('drag-image');
holder.ondragover = function () { returnfalse; };
holder.ondragend = function () { returnfalse; };
holder.ondrop = function (event) {
event.preventDefault && event.preventDefault();
//do something with:var files = event.dataTransfer.files;
console.log(files);
bottomFileAdd(files, 0);
returnfalse;
};
//Recursive function to add files in the bottom div//this code was adapted from another code, i didn't test itvar bottomFileAdd = function (files, i) {
if(!i) i=0;
if (!files || files.length>=i) return;
var file = files.item(i);
var img = document.createElement('img');
var bottom = document.getElementById('bottom'); //this string should not be static
bottom.appendChild(img);
var reader = newFileReader();
reader.onload = function (event) {
console.log(event.target);
img.src = event.target.result;
bottomFileAdd(files, i+1);
};
reader.readAsDataURL(file);
}
</script>
note: It may not work in older browsers.
I hope it helps.
Solution 3:
You tried to set the src
attribute of the <img>
tag to a local file path. However, the web browser doesn't expose the local file URL (file://...
) in the value
property of the <input>
tag. The browser implementation may vary; Chrome, for example, gives you a fake path.
You can load the image by the FileReader API into a data URI and show it by setting the src
attribute of the <img>
tag:
functionmyFunction() {
var myFile = document.getElementById("myFile");
if (myFile.files && myFile.files.length) {
if (typeofFileReader !== "undefined") {
var fileReader = newFileReader();
fileReader.onload = function(event) {
document.getElementById("myImg").src = event.target.result;
};
fileReader.readAsDataURL(myFile.files[0]);
} else {
alert("Your browser doesn't support the FileReader API.")
}
} else {
alert("No file was selected.")
}
}
You need a fairly modern web browser for this to work:
Browser Firefox Chrome IE Opera Safari
Version 3.6 7 10 12.02 6.0.2
You can have a look at a working sample page. The final implementation of such image preview should set the <img>
element to a fixed size, but your markup with my function is enough as a simple demonstration.
Post a Comment for "Display Image Using Upload Js"