Get file name on drag and drop FileReader - javascript

Hi I am using native HTML5 drag and drop to upload files to the server. I want to get the name of the file being uploaded from the local system. I am unable to get the name of the file being dropped in the drop zone. Below is the code i have tried. Any help would be appreciated
var reader = new FileReader();
reader.onload = function (event) {
var childrenDivs = document.getElementById("holder").children
var temp
if(childrenDivs.length > 0){
var lastDiv = childrenDivs[childrenDivs.length - 1]
temp = parseInt(lastDiv.id.split("_")[1]) + 1
}else{
temp = 1
}
var imageDiv = document.createElement('div')
imageDiv.id = "uploadedImage_"+temp
var image = new Image();
image.src = event.target.result;
console.log(event.target.fileName)
instead of console.log(event.target.fileName) i have also tried console.log(event.target.files[0].name) and console.log(event.dataTrasfer.files[0]). Could anyone please help me out here.

Where are you calling reader.readAs... method?
AFAIK, the proper place to get the filename would be where you register the drop event of a dom element.
element.ondrop = function(e) {
e.preventDefault();
var reader = new FileReader();
reader.onload = function (event) {
....
}
var file = e.dataTransfer.files[0];
// can get the name of the file with file.name
console.log(file.name);
reader.readAsBinaryString(file);
}

Related

How to get a gif to show up on a blob

I have a function that brings users to a blob when a button is clicked and selections are made. The point is for them to click a download button and it take them to a blob with the gif on the page made based off their selections. I have working js/html/css that creates and downloads the gif for them but I am trying to now make code that makes the gif appear on the blob. It is successfully taking users to the blob but the gif is not appearing on the page. Any help would be appreciated.
js for creating the gif and sending users to the blob.
var directory = '/directory/here';
// add an event listener for the 'change' event on the dropdown menu
dropdown_fg2.addEventListener('change', function() {
// check if the selectedValue1 and selectedValue2 variables have been assigned values
if (!isNaN(selectedValue1) && !isNaN(selectedValue2)) {
// create an array of images
var images = [];
// set the starting image
var startImage = selectedValue1;
// set the ending image
var endImage = selectedValue2;
// set the step size for the images
var step = 6;
// create a loop to add the images to the array
for (var i = startImage; i <= endImage; i += step) {
var filePath = directory +"gfs_6hr_2m_temp_hour_"+i+ '.png';
// add the image to the array
images.push(filePath);
}
const downloadButton = document.getElementById('download-button2');
// Handle the button click
downloadButton.addEventListener('click', function () {
/// Generate gif
gifshot.createGIF({
'images': images,
'gifWidth': 1144,
'gifHeight': 894,
'interval': 0.33
},function(obj) {
if(!obj.error) {
const reader = new FileReader();
// Read the contents of the image file as a ArrayBuffer
reader.readAsArrayBuffer(obj.image);
reader.onload = function() {
// Create a Blob object that represents the GIF file
const gifBlob = new Blob([reader.result], {type: 'image/gif'});
// Use the URL.createObjectURL() method to create a URL for the Blob
const gifUrl = URL.createObjectURL(gifBlob);
console.log(gifUrl)
window.open(gifUrl);
// You can then use the URL to open the GIF file in a new window or to display it on your website
// var animatedImage = document.createElement('img');
var animatedImage = document.getElementById('my-image')
animatedImage.src = gifUrl;
console.log(animatedImage)
}
});
});
console.log(images);
}
})

JavaScript reading and previewing multiple images

I have found code for reading multiple images on the
internet.
Here is the code:
HTML
<input id="browse" type="file" onchange="previewFiles()" multiple>
JavaScript
function previewFiles() {
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild( image );
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
I have a problem with it, as I do not fully understand what is happening and why it does not preview/seems like it is storing multiple files.
The main problem in the included code is that there is no element with the id preview (ref: var preview = document.querySelector('#preview');)
Adding this and it will work. However, you can skip FileReader as it isn't needed. Instead treat the File as a Blob (they are essentially the same) and use createObjectURL() with it - the performance and the memory footprint are significant better in case you want to display a high amount of images.
document.querySelector('#browse').onchange = function() {
var preview = document.querySelector('#preview');
[].forEach.call(this.files, function(file) {
if (/image\/.*/.test(file.type)) { // use any image format the browser can read
var img = new Image;
img.onload = remURL; // to remove Object-URL after use
img.style.height = "100px"; // use style, "width" defaults to "auto"
img.src = (URL || webkitURL).createObjectURL(file);
preview.appendChild(img); // add image to preview container
}
});
function remURL() {(URL || webkitURL).revokeObjectURL(this.src)}
};
<input id="browse" type="file" multiple>
<div id=preview></div> <!-- an element with this ID was missing -->
Your final lines of code:
if (files) {
[].forEach.call(files, readAndPreview);
}
Should do nothing. It goes for each over an empty array.
I think you were trying to do something like:
files.forEach(readAndPreview)
Which would actually go over all of the files in the files array and call readAndPreview for them.

Javascript image upload, need description embed

the main thing that I am trying to do is get this simple image uploader to also allow the user to enter and store a description along with the image that is uploaded. Also some way to clear the images stored once they are in the preview.
What I currently have is
<html>
<body>
<script type='text/javascript'>
function main()
{
var inputFileToLoad = document.createElement("input");
inputFileToLoad.type = "file";
inputFileToLoad.id = "inputFileToLoad";
document.body.appendChild(inputFileToLoad);
var buttonLoadFile = document.createElement("button");
buttonLoadFile.onclick = loadImageFileAsURL;
buttonLoadFile.textContent = "Load Selected File";
document.body.appendChild(buttonLoadFile);
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
main();
</script>
</body>
</html>
Any help you can give would be greatly appreciated!
To get a description just create another input element within the form. Your code is not showing how you actually upload the image. So I guess it's a form with a POST action?
To clear the image, just add a button that removes the "img" element. For ease of use, just make the "imageLoaded" global and then remove that from the DOM when pressing that button.

div backgroundImage withd input result

I'm using this tech : link to get images from local clients, i don't want save it on my server. Can i (in javascript) set a div backgroundImage width this image ?
Now this is my code :
var input9I1 = document.createElement("input");
input9I1.id = "input9I1";
input9I1.type = "file";
input9I1.name = "files[]";
input9I1.accept = "image/*";
input9I1.addEventListener('change', handleFileSelect, false);
td20I1.appendChild(input9I1);
So it was the creation of the input and it work fine.
Now the function :
function handleFileSelect(evt){
imgageATraiter = evt.target.files[0];
console.log(imgageATraiter.name);
console.log(imgageATraiter.type);
console.log(imgageATraiter.size);
console.log(imgageATraiter.lastModifiedDate);
console.log(imgageATraiter.lastModifiedDate.toLocaleDateString());
document.getElementById('boite5I1').style.backgroundImage = imgageATraiter.name;}
So what i want is how can i modify the "boite5I1" 's background with my image ? Is it possible ? Thanks to read and have a good day :D
You should try below code in handleFileSelect function.
if (imgageATraiter) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('boite5I1')
.attr('src', e.target.result)
.width(50)
.height(50);
};
reader.readAsDataURL(imgageATraiter );
}
Thanks nicael the answer is :
function handleFileSelect(evt){
imgageATraiter = evt.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
$('#boite5I1').css('background', 'transparent url('+e.target.result +') left top no-repeat');
}
reader.readAsDataURL(evt.target.files[0]);}
Thanks so much and have a good day :D

Displaying thumbnail image with plugin

I am using https://code.google.com/p/jquery-multifile-plugin/
I am trying to display the thumbnail of the image that was just selected with the following code:
$(function() {
var doc = document;
var oError = null;
var oFileIn = doc.getElementById('file-upload');
var oFileReader = new FileReader();
var oImage = new Image();
oFileIn.addEventListener('change', function () {
alert("in");
var oFile = this.files[this.files.length-1];
//rest of the code
});
It works for the first image. When I try to add another the event isn't triggered, any suggestions?

Categories