Display Image Using Upload JS - javascript

I want to display the image using the upload form and submit button.
But the problem though, I can't make the image appear.
Here's what I did.
function myFunction() {
var x = document.getElementById("myFile").value;
document.getElementById('myImg').src = document.getElementById("myFile").name;
<form>Select a file to upload:
<input type="file" id="myFile" name=filename>
</form>
<button type="button" onclick="myFunction()">Upload This</button>
<img id="myImg" src="">
I just don't know what seems to be the problem with this.
Thank you for helping me out.

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.

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 () { return false; };
holder.ondragend = function () { return false; };
holder.ondrop = function (event) {
event.preventDefault && event.preventDefault();
//do something with:
var files = event.dataTransfer.files;
console.log(files);
bottomFileAdd(files, 0);
return false;
};
//Recursive function to add files in the bottom div
//this code was adapted from another code, i didn't test it
var 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 = new FileReader();
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.

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:
function myFunction() {
var myFile = document.getElementById("myFile");
if (myFile.files && myFile.files.length) {
if (typeof FileReader !== "undefined") {
var fileReader = new FileReader();
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.

Related

get event.result for a input type file in jquery

The problem I have is that I am not getting the value of the result here; the code alerts undefined. I want to preview the image selected by user. Can someone tell me what the issue is?
<input type="file" name="file_name" style='display: none;' id='cover_image_90' onchange="chnageBGDynamic(this, 'Cover_Iamge_90op', '0');"/>
function chnageBGDynamic(file_id_ch,change_bg_id,is_aled_othr){
var files = !!file_id_ch.files ? file_id_ch.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){ // set image data as background of div
$("#"+change_bg_id).css("background-image", "url("+file_id_ch.result+")"); // here is the problem it dosent gets changed. i get a blank background and when checked by inspect element i get undefined src
$("#"+change_bg_id).css("background-size", "cover");
}}else{
if(is_aled_othr =='0'){
alert('Only Images Are Allowed to Upload '); return false;
}else{
$("#"+change_bg_id).css("background-image", "url(avator/icon/noticei.png)");
$("#"+change_bg_id).css("background-size", "85%");
$("#"+change_bg_id).css("background-repeat", "no-repeat");
}
}
}
Your code is almost correct; just need one small change:
Instead of
$("#"+change_bg_id).css("background-image", "url("+file_id_ch.result+")");
We need:
$("#"+change_bg_id).css("background-image", "url("+reader.result+")");
function chnageBGDynamic(file_id_ch,change_bg_id,is_aled_othr){
var files = !!file_id_ch.files ? file_id_ch.files : [];
if (!files.length || !window.FileReader)
return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){ // set image data as background of div
$("#"+change_bg_id).css("background-image", "url("+reader.result+")"); // here is the problem it dosent gets changed. i get a blank background and when checked by inspect element i get undefined src
$("#"+change_bg_id).css("background-size", "cover");
}}else{
if(is_aled_othr =='0'){
alert('Only Images Are Allowed to Upload '); return false;
}else{
$("#"+change_bg_id).css("background-image", "url(avator/icon/noticei.png)");
$("#"+change_bg_id).css("background-size", "85%");
$("#"+change_bg_id).css("background-repeat", "no-repeat");
}
}
}
.result is a property of FileReader object and not of input of type file
<input type="file" name="file_name" id='cover_image_90' onchange="chnageBGDynamic(this, 'Cover_Iamge_90op', '0');"/>
<script>
function chnageBGDynamic(file_id_ch, change_bg_id, is_aled_othr) {
console.log(file_id_ch.files);
console.log(file_id_ch.value);
console.log(change_bg_id);
}
</script>
use .value to see the file name and .files which will contain all the info about the image file Fiddle and you can see the output in developer tool in console tab

Javascript image upload and display

My basic task is select image and display it,without saving it in database.
For this
1.I have made a select tag in html,through which I can upload the image.
2.I have made a blank image tag in which at there is no image source,alternate is upload image.
3.select tag has onchange javascript event handler which calls javascript function changeimage.
<script>
function changeimage()
{
document.form_name.imagetag.src=document.form_name.filetag.value;
}
</script>
In above Code
form_name : Is the name of my form
<form name = "form_name">
imagetag : Is the name of my Img tag
<Img src=" " name = "imagetag">
filetag : Is the name of my
<input type="file" name = "filetag" onchange="changeimage()">
I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.
I am using window 7,wamp server and chrome latest version.
You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.
Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.
var fileTag = document.getElementById("filetag"),
preview = document.getElementById("preview");
fileTag.addEventListener("change", function() {
changeImage(this);
});
function changeImage(input) {
var reader;
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function(e) {
preview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<input type="file" id="filetag">
<img src="" id="preview">
You can also use the Image() constructor. It creates a new HTML Image Element.
Example -
document.getElementById("filetag").addEventListener("change", function(e) {
let newImg = new Image(width, height);
// Equivalent to above -> let newImg = document.createElement("img");
newImg.src = e.target.files[0];
newImg.src = URL.createObjectURL(e.target.files[0]);
output.appendChild(newImg);
});
Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
You need one input tag to upload file and a image tag to render on the site.
The HTML and Javascript should look like
const renderFile = () => {
const render = document.querySelector('img')
const file = document.querySelector('input[type=file]').files[0]
const reader = new FileReader();
reader.addEventListener('load' , ()=> {
render.src = reader.result;
}, false)
if(file){
reader.readAsDataURL(file);
}
}
<input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image' >
Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need

how to get photo compleet url form form in array

I am trying to use jquery to take a picture from my comp via a form.
- So I want the entire URL out of the form in an array
It works + / - in Dreamweaver, but not in the explorer browsers not even chrome
The end goal is a calendar with picture / app for people with disabilities, but as long as I get to go through the phone gap
var foto= new Array();
var i=-1;
//foto=["toets.png"];
$('#fotouit').append("FOTO UIT");
$('#knop01').click(function(){
$('input:file[name=foto]').each(function(){
//alert($(this).val());
foto.push($(this).val());
foto.forEach( function(){
i++;
$('#fotouit').append(foto[i]);
$('#fotouit').append('<img src=" '+ foto[i] + ' " width="100" height="100" />');
});
});
})
I don't think it is possible to get the URL of the picture in you computer's local filesystem, but you can use Javascript's FileReader API to read the contents of the uploaded file (in your case, the picture). The read contents can be used in the src of the img element as you did in your example code.
This is an in depth explanation of what you're trying to accomplish: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Example:
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img); // Assuming that "preview" is a the div output where the content will be displayed.
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
Note:
You can use the multiple attribute on a file input to allow selecting many files with one input
You can use the file inputs change event to immediately capture the files rather than providing a second button to click

Reading mp3 file duration in Chrome with JavaScript/jQuery

I have an 'browser application' where users should be able to drag and drop local mp3 files to Chrome and should see some mp3 info (without uploading files to server)...
So far, I can successfully read and display mp3 tags (with JavaScript-ID3-Reader library), but I'm struggling a bit with displaying mp3's duration. Is it possible to get that info with js/jQuery only? If not, what would you recommend for resolving this simple problem?
Code I'm using to handle dropping files to browser looks like this:
function initialize() {
var target = document;
if (target === null) {
return false;
}
target.addEventListener('drop', function(event) {
event.preventDefault();
var files = event.dataTransfer.files;
console.log(files);
for (var i = 0; i < files.length; i++) {
processFile(files[i]);
objectURL = window.URL.createObjectURL(files[i]);
console.log(objectURL);
}
}, true);
}
Thanks!
Try this
var audio = new Audio()
audio.addEventListener("timeupdate", function() {
console.log(audio.currentTime)
})
audio.addEventListener("canplaythrough", function() {
console.log(audio.duration)
})
target.on("change", function(e) {
var file = e.currentTarget.files[0]
var objectUrl = URL.createObjectURL(file)
audio.src = objectUrl
$("#duration").html(audio.duration)
})
If you are using latest browsers that support audio tag, you can load the mp3 in an <audio> element and access the duration property via the DOM.
To load a audio file to browser see: window.URL.createObjectURL

Add or remove slides using jQuery FlexSlider

Is it possible to add or remove slides in runtime using FlexSlider?
The new version of FlexSlider 2 already supports this methods.
slider.addSlide(obj, pos) accepts two parameters, a string/jQuery object and an index.
slider.removeSlide(obj) accepts one parameter, either an object to be removed, or an index.
This is just what I saw after looking at this thread.
The slider and the carousel object can be instantiated and added to like this:
$('#slider').data('flexslider').addSlide("");
$('#carousel').data('flexslider').addSlide("");
The click on the carousel to scroll to the particular image doesn't work, but the scroll buttons on both work.
The actual implementation of FlexSlider doesn't support it.
If you modify the actual implementation to return the slider object, with this object you can stop the slider, remove the slide you want and then recreate the slider.
After trying lots of different ideas, I got this solution to add or remove a new image or video in Flexslider dynamically and its working fine.
JQuery code:
$("#add2").change(function(event)
{
var fuData = document.getElementById('add2');
var files = event.target.files;
for(var i = 0; i< files.length; i++)
{
var file = files[i];
var filename = file.name;
var Extension =
filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
if(Extension == 'png' || Extension == 'jpg' || Extension == 'jpeg' || Extension == 'svg'){
var reader = new FileReader();
reader.onload = function(e)
{
var img = document.createElement("IMG");
img.src = e.target.result;
div = "<li><img src="+img.src+" /></li>";
$('.flexslider').data('flexslider').addSlide($(div));
}
}
else if (Extension == 'mp4')
{
var reader = new FileReader();
reader.onload = function(event){
var video = document.createElement("video");
video.src = event.target.result;
div = " <li><video src="+video.src+" width='100%' height='500' controls></video></li>";
$('.flexslider').data('flexslider').addSlide($(div));
}
}
else
{
alert(filename+' '+'is not in supported format');
$("#add2").val('');
}
reader.readAsDataURL(file);
}
});
function remove()
{
var slider = $('.flexslider').data('flexslider');
slider.removeSlide(slider.currentSlide);
}
HTML code:
<input type="file" id= "add2" multiple>
<button id="remove" onclick="remove()" value="Remove">Remove</button>
as per the code, with browse file, you can select multiple images and videos to add in Flexslider and with remove button, you can remove a current slide.I also added some validation so only image or video will be add in a slider. It will give an alert if you select any other extension. I created this code as per my requirement, you can customize it accordingly to your requirements.

Categories

Resources