I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>
<div class="imagePreview"></div>
<input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>
And I have javascript to handle the image preview as follows:
function handleFiles(files) {
$(".obj").remove();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var pic_div = document.getElementById("imagePreview");
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
pic_div.appendChild(img);
var reader = new FileReader();
reader.onload = (
function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}
)(img);
reader.readAsDataURL(file);
}
}
I want to replace the line:
var pic_div = document.getElementById("imagePreview");
with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.
The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:
<div id="imagePreview"></div>
Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
//Do Something
});
Or:
var pic_div = $(".imagePreview")[0]
Related
I am trying to upload image and previewing it one by one but it replace last image.
I want to keep adding up more and more images but only last image is showing in received $_FILES array
Keep all upload images in form and keep them previewing.
my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>
<script>
$(function() {
var upload_count = 0;
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
// input.files.append(input.files[i]);
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
</script>
The reason why only last images is getting uploaded is that you are storing the images in an array because you have single file upload input.
If you want upload multiple images you have previewer on form submit you would need to store them in array i have named imagesToUpload
Once you have all the images previwed and ready to submit the form with images you have selected and previewed you have loop forEach through that array imagesToUpload and append those file data to formData.
You will then this formData to your backend and upload all the images on backend using ajax request.
Run snippet below to see that array is using .push function to store all your images you have previewed.
$(function() {
var upload_count = 0;
//Store images in array
var imagesToUpload = []
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
// input.files.append(input.files[i]);
//Push images to array on preview
imagesToUpload.push(input.files[i])
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
console.log(imagesToUpload)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>
I am trying to somehow save my image generated with <input type="file" id="file_capture" capture="user" accept="image/*"/> through vb.net ajax and save the file into a file share folder.
I need image capture so that if the user is on their phone it will screen capture.
I have tried jquery-webcame with no luck and have ended with only HTML Capture working up to the point when I need to save the file.
So far the image src looks something like this data:image/jpeg;base64,/...
When I pass the src into ajax I tried to read it using Net.WebClient but I am unsure how to get the address of the img when all I have is the src value to use for My.Computer.Network.DownloadFile
VB.NET
<System.Web.Services.WebMethod(EnableSession:=True)> Public Shared Function SaveImage(ByVal src As String) As String
Try
Dim client As Net.WebClient = New Net.WebClient
Dim destination = "\\serverName\FolderShareName\"
client.DownloadFile(src, destination)
Catch ex As Exception
End Try
Return "Pass"
End Function
HTML
<label class="cameraButton" style="min-width:150px;">Capture File
<input type="file" id="file_capture" capture="user" accept="image/*"/>
</label>
<div id="imageHolder" class="col-sm-12" style="border:1px solid red;text-align:center;min-width:150px;" runat="server">
</div>
JAVASCIRPT [I created it this way so multiple images can be uploaded]
$('#file_capture').change(function () {
AddNewImage(this);
});
function AddNewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var id = $("#imageHolder > div > img").length
var fullid = "uploadImage" + id++;
var DIV = document.createElement("DIV");
DIV.className = "imgWrap"
DIV.ID = "imgWrapID" + id++;
DIV.style.display = "inline-block";
DIV.style.padding = "10px";
document.getElementById('imageHolder').appendChild(DIV);
var img = new Image(200, 200);
reader.onload = function (e) {
img.src = e.target.result;
img.id = fullid
}
reader.readAsDataURL(input.files[0]);
var btn = document.createElement("BUTTON");
btn.innerHTML = "x";
btn.className = 'top-right';
btn.name = DIV.ID
btn.title = fullid
btn.onclick = function () {
$("#" + this.name).remove();
$("#" + this.title).remove();
$(this).remove();
return false;
};
DIV.appendChild(btn);
DIV.appendChild(img);
}
}
client.DownloadFile(src, destination)
clearly won't accept the 64bit src value of the image so I need to somehow convert it to a address.
I have an array with 3 cells.At the first cell i have a textarea where you can insert the url of an image.At the second cell i have a button which when you click the image display at the third cell where i have a div to display the image.The question is how can i display the image either from the internet either from local?
The code i wrote is:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
mydiv.innerHTML = url.value;
}
<html>
<body>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
img = document.createElement('img');
img.src = document.getElementById('imagename').value;
document.body.appendChild(img);
}
</script>
</body>
</html>
You can see the sample code will add the images from an array to the document.
You could also append the images to any of the elements in your function by using url.appendChild
var arr = ['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x250','http://via.placeholder.com/350x350']; // hold image urls in an array.
arr.forEach(function(item){
// loop through array and add images to the document.
var img = new Image();
img.src = item;
document.body.appendChild(img);
});
In order to do both you would need to change your html and code.
For the case when the user has a url you can just create a new image and append it to your div setting the image's src to the url that was set in the input:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
var image = new Image;
mydiv.appendChild(image);
image.src = url.value;
}
Now to get it to display a local image you will need a file input or a drag and drop scheme as you cannot access local files without some type of user interaction.
So you would, for example, need to change your html to include a file input, and grab a reference to the selected file the user selects. Then use FileReader to read the file, and finally display it
HTML
<input type="file" id="imagefile">
JS
//input reference
var imageinput = document.getElementById("imagefile");
imageinput.addEventListener('change',function (){
var mydiv = document.getElementById("idofdivtodisplayimg");
var image = new Image;
mydiv.appendChild(image);
//FileReader instance
var reader = new FileReader;
reader.addEventListener('load',function(){
//reader.result will contain a dataURL that can be used
//like a regular image url
image.src = reader.result;
});
//read the file as a dataURL
reader.readAsDataURL( imageinput.files[0] );
});
This does both, it let's you upload an image (or at least load it to the browser) or give a URL to an image source. Click the button and the image is loaded and displayed!
This snippet uses the FileReader API to get the uploaded image and display it in an image element
function uploadOrNot() {
if (document.querySelector("input[type=file]").files[0]){
let input = document.querySelector("input[type=file]");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
display(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
} else if (document.querySelector("input[type=text]").value){
display(document.querySelector("input[type=text]").value);
}
}
function display(res) {
let img = document.createElement("IMG");
img.src=res;
document.querySelector("#result").appendChild(img);
}
<div id="urlOrUpload">
<input type="text"/>
<br>
<input type="file" accetp="image/*"/>
</div>
<div id="buttonHolder">
<button type="button" onclick="uploadOrNot()">Display</button>
</div>
<div id="result"></div>
I partly solved it by replacing the div at the third cell with an img tag and at the function i wrote above, i chenged it to:
var image = document.getElementbyId("imageid");
var url = document.getElementbyId("urlid");
image.src = url.value;
But at the table i have,i also have a button where you can add a same row as above.How can i do this function for every url that is placed at every textbox?
I have div which was dropzone to drop file(s) in the div,
<div id="dropZone"></div>
<input type="file" id=fileUpload"/>
I want to bind drop files to the html file type "fileUpload" control. I have tried like
but not getting. is it possible?
I have written the script for the div
$('#dropZone').bind('dragenter', ignoreDrag);
$('#dropZone').bind('dragover', ignoreDrag);
$('#dropZone').bind('drop', function (e) {
drop(e);
});
Edited and Added script
//Updated
function ignoreDrag(e) {
e.originalEvent.stopPropagation();
e.originalEvent.preventDefault();
}
//Updated End
and in the drop function
function drop(e) {
ignoreDrag(e);
var dt = e.originalEvent.dataTransfer;
var droppedFiles = dt.files;
if (dt.files.length > 0) {
for (var i = 0; i < dt.files.length; i++) {
var fileName = droppedFiles[0].name;
$("#lblMsg").show();
$("#spnFile").text(fileName);
var formData = new FormData();
formData.append("fileUploaded", droppedFiles);
alert(dt.files[0]);
$("#fileUploaded").bind("val", dt.files[0]);
// Binding to file(s) to the <input type="file"/> but not binding.
}
}
}
Is this possible to bind like above??
i have the following code, the issue i have is that i am getting a error of e.originalEvent.dataTransfer is undefined.
my code is as follows
HTML
Select images: <input type="file" id='fileupload' name="userfile[]" multiple>
Javascript is as follows
var hot = $('#fileupload');
hot.change(function (e)
{
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
//send dropped files to Server
handleFileUpload(files,hot);
});
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var fd = new FormData();
var e = document.getElementById("child_id");
fd.append('userfile[]', files[i]);
var filename=files[i].name;
var status = new createStatusbar(obj,files[i]); //Using this we can set progress.
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status,filename);
}
}
The attribute files belongs to the input field. This you'll get by the target attribute.
If I test the setting above, I have success with this descriptor:
e.originalEvent.target.files
Then, files is an array of File objects, containing name, lastModifiedDate, type etc.