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
Related
I'm using this awesome tutorial to preview multiple image before upload.
Now I need to put some information, file name & file size.
Below is the sample:
And the JS:
function previewImages()
{
var preview = document.querySelector('.gallery');
if(this.files)
{
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file)
{
if (!/\.(jpe?g|png|gif)$/i.test(file.name))
{
return alert(file.name + " is not an image");
}
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.width = 150;
image.height = 150;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#uploadFile').addEventListener("change", previewImages);
HTML:
<span class="btn btn-default btn-file">
Browse <input type="file" name="uploadFile" id="uploadFile" multiple="multiple"/>
</span>
<div class="gallery" style="display: flex; flex-wrap: wrap;"></div>
I know to get the file size and file name is using this: file.size & file.name.
But now how to put that information on my code?
And 1 more how to add delete button for each image and function to delete it?
I made some suggestions in a comment, but perhaps they weren't helpful. Here's a more complete answer.
Here's a simplified JSFiddle which adds some text under the image. I've just faked a placeholder image to simplify things and focus on the question you asked.
You really only need to do a few things:
1) Create an HTML element to hold your new text. If you don't add this, it won't style well under the <img>. You could add an empty container inside your gallery for text, but going by the name "gallery", it is intended for multiple pictures, so it doesn't make sense to add a bunch of empty placeholders.
You can create an element with (you could use any element of course):
var info = document.createElement("div");
2) Add text to that element. You can do that in several ways, maybe best is:
var text = document.createTextNode('your text');
info.appendChild(text)
3) Add your new element to the DOM, specifically after your new image:
preview.appendChild(info);
Putting it all together (JSFiddle), with some simplification:
var preview = document.querySelector('.gallery'),
image = new Image(),
info = document.createElement("div");
image.width = 150;
image.height = 150;
image.title = 'Foo Title';
image.src = 'https://via.placeholder.com/150';
info.appendChild(document.createTextNode(image.title));
info.appendChild(document.createElement("br"));
info.appendChild(document.createTextNode(image.width + ' x ' + image.height + 'px'));
preview.appendChild(image);
preview.appendChild(info);
I'm a newbie in html/javascript and made two buttons that can upload image (choose file button and upload button).
However, I want to make it to just a single button and don't know how to combine those two button. I already searched on google, they said we can use onchange to combine submit button but I already have onchange function that can show image right away after choosing image file to iframe.
Here is my html code for <form>
<form action="/upload", method="post", enctype="multipart/form-data">
<div style='height:0px; width:0px; overflow:hidden;'><input type="file" name="upFile" id="upFile" onchange="getCmaFileView(this, 'name').submit()" target="dropzone_1"/></div>
</form>
Also, here is my script and button
<script type = "text/javascript">
function getFile(){
document.getElementById("upFile").click();
}
</script>
...
<li><a onclick="getFile()" style="cursor:pointer; color:#000000;">Choose File</a></li>
I tried with adding .submit() in onchange, but it didn't work.
Does anybody have an idea for this?
Please please help me out here!
Thanks in advance.
EDIT
function getCmaFileInfo(obj,stype) {
var fileObj, pathHeader , pathMiddle, pathEnd, allFilename, fileName, extName;
var file;
var img, reader;
// file = upload.files[0];
upload = document.getElementsByTagName('input')[0];
holder = document.getElementById('dropzone');
reader = new FileReader();
file = upload.files[0];
var iupload, holder;
reader.onload = function (event) {
img = new Image();
//console.log(event.target.result);
img.src = event.target.result;
img.width = document.getElementById("dropzone").clientWidth;
img.height= window.innerHeight;
// note: no onload required since we've got the dataurl...I think! :)
holder.innerHTML = '';
holder.appendChild(img);
};
reader.readAsDataURL(file);
}
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
}
Can't you just add one more function/code in your getCmaFileView() - Which will just submit the form? Also it will be called after your image viewing part is done so that may solve your problem.
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
//form.submit() OR call_to_your_submit_function();
}
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
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.
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.