Image upload on file chosen not on submit form , [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a HTML form where the user can upload an image in the input field and it works fine but the image is uploaded when the form is submitted.
Is there a way where I can get the image to upload to the TMP directory when the file is chosen and the user is still filling out the form then when the user submits the form it can be moved to the actual file directory. This would make for a better user experience and especially people with slow internet connections would benefit from this as it would utilise the users time for effectively and efficiently.
I am not sure exactly but I think this would need some sort of jQuery/Ajax solution to upload the image mid form entry then use PHP to transfer the file from the TMP to the actual directory.

As Diodeus suggested, putting the form in an iframe would prevent it from posting in the current page frame and allow users to work on other form items. A solution more to what you were expecting would be using an AJAX request. You could look into the HTML5 API, there are many different already-built solutions and many tutorials.
Here's a simple example taken from this demo at html5demos.com
<title>Drag and drop, automatic upload</title>
<style>
#holder { border: 10px dashed #ccc; width: 300px; min-height: 300px; margin: 20px auto;}
#holder.hover { border: 10px dashed #0c0; }
#holder img { display: block; margin: 10px auto; }
#holder p { margin: 10px; font-size: 14px; }
progress { width: 100%; }
progress:after { content: '%'; }
.fail { background: #c00; padding: 2px; color: #fff; }
.hidden { display: none !important;}
</style>
<article>
<div id="holder">
</div>
<p id="upload" class="hidden"><label>Drag & drop not supported, but you can still upload via this input field:<br><input type="file"></label></p>
<p id="filereader">File API & FileReader API not supported</p>
<p id="formdata">XHR2's FormData is not supported</p>
<p id="progress">XHR2's upload progress isn't supported</p>
<p>Upload progress: <progress id="uploadprogress" min="0" max="100" value="0">0</progress></p>
<p>Drag an image from your desktop on to the drop zone above to see the browser both render the preview, but also upload automatically to this server.</p>
</article>
<script>
var holder = document.getElementById('holder'),
tests = {
filereader: typeof FileReader != 'undefined',
dnd: 'draggable' in document.createElement('span'),
formdata: !!window.FormData,
progress: "upload" in new XMLHttpRequest
},
support = {
filereader: document.getElementById('filereader'),
formdata: document.getElementById('formdata'),
progress: document.getElementById('progress')
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/gif': true
},
progress = document.getElementById('uploadprogress'),
fileupload = document.getElementById('upload');
"filereader formdata progress".split(' ').forEach(function (api) {
if (tests[api] === false) {
support[api].className = 'fail';
} else {
// FFS. I could have done el.hidden = true, but IE doesn't support
// hidden, so I tried to create a polyfill that would extend the
// Element.prototype, but then IE10 doesn't even give me access
// to the Element object. Brilliant.
support[api].className = 'hidden';
}
});
function previewfile(file) {
if (tests.filereader === true && acceptedTypes[file.type] === true) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
image.width = 250; // a fake resize
holder.appendChild(image);
};
reader.readAsDataURL(file);
} else {
holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
console.log(file);
}
}
function readfiles(files) {
debugger;
var formData = tests.formdata ? new FormData() : null;
for (var i = 0; i < files.length; i++) {
if (tests.formdata) formData.append('file', files[i]);
previewfile(files[i]);
}
// now post a new XHR request
if (tests.formdata) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/devnull.php');
xhr.onload = function() {
progress.value = progress.innerHTML = 100;
};
if (tests.progress) {
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
progress.value = progress.innerHTML = complete;
}
}
}
xhr.send(formData);
}
}
if (tests.dnd) {
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
readfiles(e.dataTransfer.files);
}
} else {
fileupload.className = 'hidden';
fileupload.querySelector('input').onchange = function () {
readfiles(this.files);
};
}
</script>
This creates a zone to drop a file (instead of a browse button) and initiate the file upload when the drag and drop event occurs. It will do it asynchronously and allow the page contents to be interacted with as normal while the transfer proceeds in the background. There is an important thing in this example to change, however. This line:
xhr.open('POST', '/devnull.php');
Should be changed to a code file in your environment/server that will process the file upload data and save or process the file however you need. This script merely acts as a front-end to that script. Another thing to remember is the HTML5 File API is still a modern-browser-only type of thing; it's well supported in current browsers, but older ones are out of luck. If you need to have them supported, you should look for another solution.

Related

Make File Uploader/Preview Handle Multiple Files

I've built a file uploader (that runs on php in the backend) that previews an image file prior to upload.
The problem I'm having is I can't get it work with multiple files.
It's based on a tutorial I watched and the crux of the issue is in the updateThumbnail function. When this function is called for multiple file uploads I think I need to change the second parameter from fileUploader.files[0] to fileUploader.files, but I'm struggling with the actual function itself.
I clearly need to run a foreach loop (or similar) in the updateThumbnail function but I can't get it to play ball.
Note: It seems CodePen doesn't allow drag & drop functionality, but there is an input file element that is also assigned to the drop-zone that is hidden in the HTML with display:none. This uses a click event listener and fileUploader.click() so when you click the drop-zone you can bring up the file picker window.
Codepen: https://codepen.io/pauljohnknight/pen/JjNNyzO
// hidden on the form, but has drag & drop files assigned to it
var fileUploader = document.getElementById("standard-upload-files");
var dropZone = document.getElementById("drop-zone");
var showSelectedImages = document.getElementById("show-selected-images");
dropZone.addEventListener("click", (e) => {
//assigns the dropzone to the hidden input element so when you click 'select files' it brings up a file picker window
fileUploader.click();
});
fileUploader.addEventListener("change", (e) => {
if (fileUploader.files.length) {
// this function is further down but declared here and shows a thumbnail of the image
updateThumbnail(dropZone, fileUploader.files[0]);
}
});
dropZone.addEventListener('dragover', e => {
e.preventDefault()
})
dropZone.addEventListener('dragend', e => {
e.preventDefault()
})
// When the files are dropped in the 'drop-zone'
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
// assign dropped files to the hidden input element
if (e.dataTransfer.files.length) {
fileUploader.files = e.dataTransfer.files;
}
// function is declared here but written further down
updateThumbnail(dropZone, e.dataTransfer.files[0]);
});
// updateThumbnail function that needs to be able to handle multiple files
function updateThumbnail(dropZone, file) {
var thumbnailElement = document.querySelector(".drop-zone__thumb");
if (!thumbnailElement) {
thumbnailElement = document.createElement("img");
thumbnailElement.classList.add("drop-zone__thumb");
// append to showSelectedImages div
showSelectedImages.appendChild(thumbnailElement);
}
if (file.type.startsWith("image/")) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
thumbnailElement.src = reader.result;
};
} else {
thumbnailElement.src = null;
}
} // end of 'updateThumbnail' function
body {
margin: 0;
display: flex;
justify-content: center;
width: 100%;
}
form {
width: 30%;
}
#drop-zone {
border: 1px dashed;
width: 100%;
padding: 1rem;
margin-bottom: 1rem;
}
.select-files {
text-decoration: underline;
cursor: pointer;
}
/* image that is preview prior to form submit*/
.drop-zone__thumb {
width: 200px;
height: auto;
display: block;
}
#submit-images {
margin-top: 1rem;
}
<form id="upload-images-form" enctype="multipart/form-data" method="post">
<h1>Upload Your Images</h1>
<div id="drop-zone" class="drop-zone flex">
<p class="td text-center">DRAG AND DROP IMAGES HERE</p>
<p>Or</p>
<p class="select-files">Select Files</p>
</div>
<div id="show-selected-images"></div>
<div class="inner-input-wrapper">
<div class="upload-label-wrapper">
<input id="standard-upload-files" style="display:none" type="file" name="standard-upload-files[]" multiple>
</div>
<input type="submit" name="submit-images" id="submit-images" value="SUBMIT IMAGES">
</div>
</form>
I did quick Codesandbox example from your Codepen
Yes, you just need to iterate over your files and for each file add a preview. You can use for loop or just use Array.from and then .forEach (because FileList is not really an array, you need to convert it to array first to be able to use array inbuilt methods)
Array.from(fileUploader.files).forEach((file) => {
updateThumbnail(dropZone, file);
});
As for previews and updateThumbnail function - it all depends on how you want to use it. If you want users to be able to add more files after first selection then you can just append new previews. If you want to clear the old ones if the user select new ones then you would need to delete old previews. Or maybe you could add "Delete" button for each preview so the user could delete one of them after adding.
Here is the variant when you just want to append new previews:
function updateThumbnail(dropZone, file) {
if (file.type.startsWith('image/')) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
var thumbnailElement = document.createElement('img');
thumbnailElement.classList.add('drop-zone__thumb');
thumbnailElement.src = reader.result;
showSelectedImages.appendChild(thumbnailElement);
};
}
}
For drop you basically do the same:
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
// .. do whatever you want or need here
Array.from(e.dataTransfer.files).forEach((file) => {
updateThumbnail(dropZone, file);
});
});
As you can see functions for handling drop and select are quite similar, you can even make separate function which accepts fileList and then do something with it, so would not need to duplicate your code for both cases.
Made some minor changes to #Danila's version
Most notable differences is the use of es6 and a way to load image faster using URL.createObjectURL. The File reader is pretty much a legecy thing now when there is object urls + new promise based read methods on the prototype itself. Using bae64 is a waste of time decoding/encoding to/from base64
https://codesandbox.io/s/httpsstackoverflowcomquestions68416563-forked-o5spy?file=/src/index.js
import "./styles.css";
// Query all needed elements in one go
const [dropZone, showSelectedImages, fileUploader] = document.querySelectorAll(
"#standard-upload-files, #drop-zone, #show-selected-images"
);
dropZone.addEventListener("click", (evt) => {
// assigns the dropzone to the hidden input element so when you click 'select files' it brings up a file picker window
fileUploader.click();
});
// Prevent browser default when draging over
dropZone.addEventListener("dragover", (evt) => {
evt.preventDefault();
});
fileUploader.addEventListener("change", (evt) => {
// Clear the already selected images
showSelectedImages.innerHTML = "";
// this function is further down but declared here and shows a thumbnail of the image
[...fileUploader.files].forEach(updateThumbnail);
});
dropZone.addEventListener("drop", (evt) => {
evt.preventDefault();
// Clear the already selected images
showSelectedImages.innerHTML = "";
// assign dropped files to the hidden input element
if (evt.dataTransfer.files.length) {
fileUploader.files = evt.dataTransfer.files;
}
// function is declared here but written further down
[...evt.dataTransfer.files].forEach(updateThumbnail);
});
// updateThumbnail function that needs to be able to handle multiple files
function updateThumbnail(file) {
if (file.type.startsWith("image/")) {
const thumbnailElement = new Image();
thumbnailElement.classList.add("drop-zone__thumb");
thumbnailElement.src = URL.createObjectURL(file);
showSelectedImages.append(thumbnailElement);
}
} // end of 'updateThumbnail' function

How to read a local file in JQuery or JavaScript?

I have an HTML file, which I want to read and append as HTML. I have tried the below codes but these codes are not working.
Approach 1:
var file = "abc.html";
var str = "";
var txtFile = new File(file);
txtFile.open("r");
while (!txtFile.eof) {
// read each line of text
str += txtFile.readln() + "\n";
}
$('#myapp').html(str);
Approach 2:
var file = "abc.html";
var rawFile = new XMLHttpRequest();
alert('33333333');
rawFile.open("GET", file, false);
alert('44444');
rawFile.onreadystatechange = function () {
alert('5555555555');
if (rawFile.readyState === 4) {
alert('66666666666');
alert(rawFile.readyState);
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
$('#myapp').html(allText);
alert(allText);
}
}
}
rawFile.send(null);
In Approach 2, it not going into the onreadystatechange method.
I thought another approach that I will use all the abc.html file content as a string variable and do similar $('#myapp').html(allText);, but this looks very bad approach because later I need to do the same for other 10-15 files. So Could you guys help me out?
Note: My application is running in offline mode means I cannot use the internet.
I have tried this solution, but its also not working.
It is not possible as JavaScript is frontend framework and it doesn't have access to local file system.
But you can do diffrent method.
-> you can serve that file in a local server and use http request with any backend framework.
I think you can adapt this pen to use as you wish:
https://codepen.io/alvaro-alves/pen/wxQwmg?editors=1111
CSS:
#drop_zone {
width: 100px;
height: 100px;
background: #000;
background-repeat: no-repeat;
background-size: 100px 100px;
opacity: 0.5;
border: 1px #000 dashed;
}
HTML:
<html>
<body>
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
</div>
</body>
</html>
JS:
//drop handler do XML
function dropHandler(ev) {
ev.preventDefault();
var file, reader, parsed, emit, x, endereco;
if (ev.dataTransfer.items) {
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
if (ev.dataTransfer.items[i].kind === 'file') {
file = ev.dataTransfer.items[i].getAsFile();
reader = new FileReader();
reader.onload = function() {
parsed = new DOMParser().parseFromString(this.result, "text/xml");
console.log(parsed);
};
reader.readAsText(file);
console.log('... file[' + i + '].name = ' + file.name);
}
}
}
removeDragData(ev)
}
function dragOverHandler(ev) {
ev.preventDefault();
}
function removeDragData(ev) {
if (ev.dataTransfer.items) {
ev.dataTransfer.items.clear();
} else {
ev.dataTransfer.clearData();
}
}
You will just to handle the result.

How to: HTML / jQuery - File upload (images) preview name + file

I do welcome constructive criticism and suggestions for different methods of completing this task.
I'm trying to write some jQuery that will allow users to preview a file or multiple files within the current window without the DOM being reloaded.
To achieve this, the simplest way I know, to .append() an image element within <div id="gallery">. I found myself struggling to get the file names to be displayed along with the correct picture, the main issue was that the pictures rendered in no particular order (probably whichever file was smallest was rendered first).
Luckily I stumbled across this post, HTML5 FileReader how to return result? and managed to adapt the code so that it rendered the picture instead of the base64 encoding.
$(function(){
$('#file_input').change(function(e){
var files = $(this.files)
$(this.files).each(function(i){
readFile(files[i], function(e) {
var imageSrc = e.target.result
$('#output_field').append('<h4>'+files[i].name+'</h4><img class="preview-thumbs" id="gallery-img" src="' + imageSrc + '">');
})
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsDataURL(file);
}
});
.preview-thumbs {display: block; padding: 10px 0px; width: 250px;}
.thumb-containers {}
#gallery>.img-container {display: inline-block; border: 3px solid #243d51; padding: 5px; width: 350px; border-radius: 20px; text-align: center;}
h4 {color: red; font-size: 20px; font-weight: bold;}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="file" id="file_input" class="foo" multiple/>
<div id="output_field" class="foo"></div>
My question here is:
Is there (if any) better way of completing this task?
Cheers in advance,
Swift
I recently publish a project that solves the exactly same problems.
I manage the file upload in a separate class that also covers Drag / Drop. Basically, you must return target.result on the "load" event.
const fileReader = new FileReader();
fileReader.addEventListener("load", this.fileReader_load.bind(this, file.name), false);
fileReader.readAsDataURL(file);
fileReader_load(fileName, event) {
event.target.removeEventListener("load", this.fileReader_load);
this.onFileLoaded(fileName, event.target.result);
}
See the full image loader here: https://github.com/PopovMP/image-holder/blob/master/public/js/file-dropper.js
The image preview is easy. Make an image element and set its src to the imageData.
Here is the full source code: https://github.com/PopovMP/image-holder
$(function(){
$('#file_input').change(function(e){
var files = $(this.files)
$(files).each(function(i, file){
readFile(file, function(e) {
var imageSrc = e.target.result
$('#output_field').append('<div class=""img-container"> <h4>'+file.name+'</h4><img class="preview-thumbs" id="gallery-img" src="' + imageSrc + '"/></span>');
})
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsDataURL(file);
}
});
This is the jQuery code amended as per the suggestion in the comments about duplication. If you post that as an answer, I will accept 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