Pass data of dropped files inside a div to another page - javascript

document.getElementById('drag_drop').ondrop = function(event)
{
event.preventDefault();
var form_data = new FormData();
var drop_files = event.dataTransfer.files;
for(var count = 0; count < drop_files.length; count++)
form_data.append("images[]", drop_files[count]);
var ajax_request = new XMLHttpRequest();
ajax_request.open("post", "upload.php");
ajax_request.send(form_data);
}
#drag_drop{
background-color : #f9f9f9;
border : #ccc 4px dashed;
line-height : 250px;
padding : 12px;
font-size : 24px;
text-align : center;
}
<div id="drag_drop">Drag & Drop File Here</div>
This code allow you to upload files using the "drag and drop" function: I drop the files in the apposite div (#drag_drop) and with JS I create a POST request to the PHP file that will upload the files...
What I want to do is that as soon as the user drops the files redirect to ANOTHER html page containing the script and then send the request to the PHP file.
I have no idea how not to lose the data of the files dropped inside the div during the page change (maybe inserting form_data/drop_files in a localstorage item... (?)).
NO JQUERY.

I have not tested this, but when you upload a file to your browser, you can use createObjectURL() to create a local URL where your file resides.
You can save this URL in the localStorage (or similar) and read it on the other page again.
const selectedFile = document.getElementById('input').files[0];
const objectURL = window.URL.createObjectURL(selectedFile);
localStorage.setItem('UPLOADED_FILE', objectURL);
// ... change page
const retrievedUrl = localStorage.getItem('UPLOADED_FILE');

Related

dynamically adding a button in html page with simple Javascript without any framework or library

hey there i'm making a simple webpage which requires to download an output image file at the last step..
but i don't know how can i add download button dynamically at correct time, because at starting of a page there is no need of download button..
so i have main.js file:
which looks something looks like this:
let img_code=document.getElementById('img_code');
let textbox=document.getElementById('textbox');
let gen_button_img=document.getElementById("img_button");
gen_button_qr.addEventListener("click",()=>
{
var trailer=textbox.value;
var url='www.example.com';
var result= url.concat(trailer);
if (navigator.onLine)
{
if(trailer.length<=1725 && trailer.length>0)
{
if((trailer !="0")&& (trailer.replace(/\s/g, '').length))
{
image_code.src=result;
alert("Image Generated successfully");
/**/
}
else
{
alert("You cannot create this file spaces only or only with single 0");
}
}
else
{
alert("Maximum charecter limit is exceeded!! ");
}
}
else
{
alert("No Internet Connection");
}
});
So, i have the question is there any way to dynamically add the button which takes file URL as input and download that file through web browser's downloader?
Note=>
I can easily save the result by right click on the picture and save image option; but i want to add an extra button to download the same file.
Most of the things explained in comments so read it first
// arrow function to create and append download button into any element
// it only takes url of file that will download.
const createBtn = (URL) => {
// create button element
const downloadBtn = document.createElement("button");
// you can set any name of id according to your choice
downloadBtn.setAttribute("id", "downloadBtn");
// create anchor element
const downloadLink = document.createElement("a");
// set any thing in inner text
downloadBtn.innerText = "Download Image";
// set download attribute to true
downloadLink.setAttribute("download", true);
// set url with URL
downloadLink.setAttribute("href", URL);
// append button element into anchor element
downloadLink.appendChild(downloadBtn);
// get that element in which download button will append
const container = document.getElementById("container");
// append download button into any element of your choice
container.appendChild(downloadLink);
};
// url of file
const URL = "https://images.pexels.com/photos/863963/pexels-photo-863963.jpeg?cs=srgb&dl=pexels-blaque-x-863963.jpg&fm=jpg"
// call createBtn function with URL
createBtn(URL);
<!-- The element in which download button will be appended -->
<div class="container" id="container"></div>
I am not 100% sure that this will work!
It also not work in stack snippet because iframe tag.
Try to use it locally.

Can I let a user set a local file as the background image for a div in javascript [duplicate]

This question already has answers here:
how to change the background image of div using javascript?
(9 answers)
Closed 1 year ago.
I want a user to select a background image from his local drive using javascript
He can set an image (id='imageID') as shown below
html
java script
image_file.onchange = function() {
var files = this.files;
var file = URL.createObjectURL(files[0]);
imageID.src = file;}
But if I change the 'target' in to the backgroundImage of a div by changing the last line to the one shown below, it does not work...
document.getElementById('divID').style.backgroundImage.src= file;
Try using a url() function in CSS to set style.backgroundImage (which is CSS property not an Image object. It is also a good idea to revoke object URLs that are no longer being used - they attach a blob object to the document and take up memory.
"use strict";
let oldURL = null;
function catchDrag(event) {
event.dataTransfer.dropEffect = "copy"
event.preventDefault();
}
document.body.addEventListener("dragenter", catchDrag);
document.body.addEventListener("dragover", catchDrag);
document.body.addEventListener("drop", function( event) {
event.preventDefault();
event.stopPropagation();
const file = event.dataTransfer.files[0];
let newURL = URL.createObjectURL( file);
if( oldURL) {
URL.revokeObjectURL(oldURL);
}
oldURL = newURL;
document.getElementById("divID")
.style.backgroundImage = `url("${newURL}")`;
});
#divID {
width: 400px;
height: 300px;
border: medium solid grey;
background-size: contain;
}
Drag and drop an image onto this page to set the background of this box:
<div id="divID"></div>

How to preview a file in different pages with one selection in JS

I am making a PDF Viewer. I am using ADOBE View SDK. I have a File input but the problem is that I want to show the file in different views - Full Screen, Half Screen and In-Line. But when the user selects a file and selects a different view the whole page reloads and then the user has to select the file again. I don't want the user to select the file again.
File Input:
<input type='file' onchange="listenForFileUpload(this);" id="file-picker" accept="application/pdf">
listenForFileUpload function:
var fileToRead = document.getElementById("file-picker");
fileToRead.addEventListener("change", function (event) {
var files = fileToRead.files;
var input = document.getElementById('file-data').value
input = files
console.log(files)
document.getElementById('file-form').submit()
if (files.length > 0 && isValidPDF(files[0])) {
var fileName = files[0].name;
var reader = new FileReader();
reader.onloadend = function (e) {
var filePromise = Promise.resolve(e.target.result);
previewFile(filePromise, fileName);
};
reader.readAsArrayBuffer(files[0]);
}
}, false);
}
Please help me to change the view without reloading.
It's this line here:
document.getElementById('file-form').submit()
You are submitting the form there. I'd just remove it.

How to dynamically create downloadable link from user uploaded files (disregarding file types) without calling server?

HTML:
<input id="browse" type="file" multiple>
<div id="preview"></div>
Javascript:
var elBrowse = document.getElementById("browse");
var elPreview = document.getElementById("preview");
function readFile(file) {
//Create downloadable link and generate DOM elements.
var fileName = file.name;
elPreview.insertAdjacentHTML("beforeend", "<a>" + fileName + '</a>');
elPreview.insertAdjacentHTML("beforeend", "<a>Delete</a><br>");
}
elBrowse.addEventListener("change", function () {
var files = this.files;
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for (var i = 0; i < files.length; i++) {
var file = files[i];
readFile(file);
}
}
});
I am facing a new requirement, but I don't have much experience in Javascript. Basically, I want users to be able to upload files by clicking the browse button and displays the files name with downloadable link. User can upload files of any type and be able to download the files back.
The whole process MUST not trigger the backend server and everything has to be done in javascript or JQuery. Could anyone help please? Thank you.
System and User interaction:
User uploads a file
System saves the file in javascript and displays the file name with downloadable link.
User delete it.
System removes it from DOM and javascript
User can repeat step 1-4. The whole process does not trigger the server at all.
Eventually, user submits all the files to the server by clicking somewhere else (This step is out of the scope of this post)
If you are using a modern browser then you can utilize the HTML5 FileReader. I've used it, but found an example more suited to your question here.
You can use the FileReader to read the files on the client side, and store in sessionStorage, localStorage, or even a variable. But the one caveat is that you'll probably run out of RAM because JavaScript's not really designed for retaining large BLOBs in RAM.
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 100%;
background: #333;
}
#page-wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
min-height: 300px;
border-top: 5px solid #69c773;
box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}
h1 {
margin-top: 0;
}
img {
max-width: 100%;
}
#fileDisplayArea {
margin-top: 2em;
width: 100%;
overflow-x: auto;
}
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>

Filereader - upload same file again not working

I have sth like drawing app. User can save projects and then load them. When I load first time one file (for e.g. project1.leds) make some changes in the app but no saving it and then again load same file (project1.leds) nothing happen. I cant load same file more than once. If I load another file, it's working.
Code:
$("#menu-open-file").change(function(e){
var data=[];
var file = null;
file = e.target.files[0];
console.log(file)
var reader = new FileReader();
reader.onload = function(e){
data=JSON.parse(reader.result);
x=data[0].SIZE[0];
y=data[0].SIZE[1];
if(x==15) x=16;
if(x==30) x=32;
if(x==60) x=64;
if(y==15) y=16;
if(y==30) y=32;
if(y==60) y=64;
createLeds(x,y,data,false,false);
clearActiveTools();
var svg = $('#contener').find('svg')[0];
svg.setAttribute('viewBox','0 0 ' + x*20 + ' ' + y*20);
$("#contener").css("width",x*20).css("height",y*20);
$("#contener").resizable({
aspectRatio: x/y,
minHeight: 200,
minWidth: 200,
});
wiFirst = $("#contener").width();
hiFirst = $("#contener").height();
}
reader.readAsText(file);
});
Can i delete/remove cached file? Is it even cached in browser?
It is because you're calling the function onchange. If you upload the same file the value of the file input has not changed from the previous upload and therefore isn't triggered. This also explains why it works if you upload a different file. No need to clear cache, you can work around this by resetting the input field's value after you read the file.
$("#menu-open-file").change(function(e){
var data=[];
var file = null;
file = e.target.files[0];
if(file !== ''){
console.log(file)
var reader = new FileReader();
reader.onload = function(e){
data=JSON.parse(reader.result);
x=data[0].SIZE[0];
y=data[0].SIZE[1];
if(x==15) x=16;
if(x==30) x=32;
if(x==60) x=64;
if(y==15) y=16;
if(y==30) y=32;
if(y==60) y=64;
createLeds(x,y,data,false,false);
clearActiveTools();
var svg = $('#contener').find('svg')[0];
svg.setAttribute('viewBox','0 0 ' + x*20 + ' ' + y*20);
$("#contener").css("width",x*20).css("height",y*20);
$("#contener").resizable({
aspectRatio: x/y,
minHeight: 200,
minWidth: 200,
});
wiFirst = $("#contener").width();
hiFirst = $("#contener").height();
}
reader.readAsText(file);
$("#menu-open-file")[0].value = '';
}
});
because input is caching the same file value so when you load the same file again it uses the cache to read value property. all you need to do is set a conditional statement when you use input element and set the value property of input to an empty string and it should work
input.value = "";
and if you are using an event handler then
e.target.value = "";
Try the below code, It should work. While clicking the upload button clear the existing value.
$("#menu-open-file").click(function(e){
$('#menu-open-file').val('');
}
The only problem with the above answer is that your HTML will no longer display the file name after the upload. Instead, it will continue to say "No file chosen", which might be confusing for users.
To get around this, you can hide the input and replace it with a label that replicates the display of the input, like so:
HTML:
<input type="file" id="myFileInput" />
<label id="myFileLabel" for="myFileInput">Choose file</label><span id="myFileName">No file chosen</span>
CSS:
#myFileInput {
display: none;
}
#myFileLabel {
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
margin-top: 5px;
padding-left: 6px;
padding-right: 6px;
}
#myFileName {
margin-left: 5px;
}
JavaScript:
var file = null
file = e.target.files[0];
//variable to get the name of the uploaded file
var fileName = file.name;
//replace "No file chosen" with the new file name
$('#myFileName').html(fileName);
well explained article how to do this here: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/
In Mozilla, everything was OK. But in Chrome, I faced the same problem:reader.onload was not uploading the same file a second time on the change event.
I was using pure javascript, and here is my solution!
HTML:
<input type="file" accept="image/*" name="image" id="file-input"/>
Javascript:
const fileInput = document.getElementById("file-input");
// My EventListener with change event and my_function
fileInput.addEventListener("change", my_function);
// reader.onload was used in my_function
//################### THIS IS THE SOLUTION ###################
// Add this EventListener to fix the problem with chrome
fileInput.addEventListener("click", function() {
fileInput.value = "";
});

Categories