drag and drop post multiples files - javascript

I would like to create a form with drag and drop functionality.
I see filelist is a read-only object and it's and it's not used with drag and drop. So I copy the file into an array and pass it to my form with formdata. But It doesn't work.
Any ideas?
html :
<form id="upload" action="action.php" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>HTML File Upload</legend>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
</fieldset>
</form>
<button id="submitbutton" >Upload Files</button>
<div id="messages">
<p>Status Messages</p>
</div>
a reduce of javascript :
var myfiles = [];
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
myfiles.push(f);
ParseFile(f);
}
}
$id("submitbutton").onclick = function(){
var xhr = new XMLHttpRequest();
formData = new FormData(document.querySelector('form'));
xhr.open('get','action.php');
formData.append("files", myfiles);
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(formData);
}

You must append files to FormData one at a time. The syntax used is similar to what you do in your input element and looks like an array. So append your files like this:
myfiles.forEach(file=>{
formData.append("files[]", file);
});
Then, on the server side they will be available in the files array.

Related

I want to remove files from object

I created a multiple file upload form. And it shows me the list of files I'm about to upload once I've selected the files. and i made delete file button to remove files that have been deleted from the object but cannot be deleted
<input type="file" class="" id="fileInput" multiple onchange="displayFiles()" style="width: 85px">
function removeFile(index) {
var input = document.getElementById("fileInput");
Array.from(input.files).splice(index, 1);
displayFiles();
}
I tried this method and it didn't work.
function removeFile(index) {
var input = document.getElementById("fileInput");
delete input.files[index];
displayFiles();
}
please help me
Hopefully this small example helps, you could create an array of indices to skip which are used when uploading.
const get = str => document.querySelector(str);
get("#myFiles").addEventListener("change", e => {
get("#howMany").setAttribute("max", e.target.files.length);
});
get("#upload").addEventListener("click", () => {
const files = get("#myFiles").files;
const len = get("#howMany").value;
const data = new FormData();
for (let i = 0; i < len; i++) {
const targetFile = files[i];
data.append("files[]", targetFile, targetFile.name);
}
devFetch("testurl", {
method: "POST",
body: data
});
});
/* DEV FETCH EMULATE NORMAL FETCH FOR STACK SNIPPET, SHOULD JUST BE FETCH */
function devFetch(url, options) {
console.log("Posting to", url, "with method", options.method);
console.log("Body:");
console.log(options.body.getAll("files[]"));
}
<input id="myFiles" type="file" multiple /> <br />
<input id="howMany" type="range" min=0 max=0 /> <br />
<button id="upload">upload</button>

input "submit" does not upload files when using onsubmit attribute

In this snippet onsubmit is used to display the image uploaded and to keep it visible return false; is used.
<form method="POST" enctype="multipart/form-data" onsubmit="display();return false;">
<input type="file" name="file" id="file">
<input type="submit" value="Upload">
</form>
JavaScript:
function display() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
// it's onload event and you forgot (parameters)
reader.onload = function(e) {
// the result image data
document.getElementById("img").src = e.target.result;
}
// you have to declare the file loading
reader.readAsDataURL(file);
}
When doing so, the image loads and is displayed but does not upload to the directory of uploads specified.
How can I upload the actual images and show the image without the need of page refresh?
Rather than changing the img after submission or manipulating a submit button I found that it's better to just use this:
<input type="file" name="file" id="file" onchange="preview_image(event)">
And then in js simply read it onchange
function preview_image(event) {
var reader = new FileReader();
reader.onload = function() {
document.getElementById('img').src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}

Handling file parse and upload on form submit

I'm parsing an Excel file to an array in JavaScript and I have a simple form with a file upload and check boxes. I'm adapting the code from elsewhere and it runs perfectly as expected immediately on file upload, but I want it to handle the file on clicking submit, not on addEventListener for "change". How can I alter this JavaScript / jQuery so that it executes the handleFile in the same way it does now, but on the form submit click.
I tried multiple methods like
document.getElementById('submit').addEventListener("click", handleFile(oFileIn));
And encapsulating everything beneath setup in:
$('#submit').click(function(){
var oFileIn; ...
});
HTML:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.12.6/xlsx.full.min.js"></script>
</head>
<body>
<form id="formid" action="form.php" method="POST" enctype="multipart/form-data">
<label><input id="inputX1" type="checkbox" name="x1" value="x1">x1</label><br>
<label><input id="inputX2" type="checkbox" name="x2" value="x2">x2</label><br>
<label><input id="inputX3" type="checkbox" name="x3" value="x3">x3</label><br>
<label><input id="inputX4" type="checkbox" name="x4" value="x4">x4</label><br>
<input id="fileid" type="file" name="filename" />
<input id="submit" type="button" value="submit"/>
</form>
</body>
</html>
JavaScript:
$(document).ready(function() {
setup();
});
function setup() {
var oFileIn;
$(function() {
oFileIn = document.getElementById('fileid');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', handleFile, false);
}
});
var rABS = true;
function handleFile(e) {
var files = e.target.files, f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
if(!rABS) data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
// DO STUFF WITH THE FILE HERE AND CHECK BOXES HERE
So if you want to just load the data on a button click all you really need to do is put a click listener on your button instead of a change event on your file input.
Your attempt was close but since we can use the ID of the file input, there is no need to pass anything into handleFile()
I also put in a check to make sure a file is actually there before we go ahead and read it.
Here's an example using jQuery for you
function setup() {
$("#submit").on("click", handleFile);
var rABS = true;
function handleFile() {
var files = $("#fileid").prop("files");
if(files.length === 0){
alert("Please select a file first");
return;
}
var f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
//continue on with data
}
reader.readAsText(f);
}
}

Angular4 File upload with fom submission.?

This is my .html file
<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
<div class="row">
<div class="col-md-12 col-12">
<label>My name is</label>
</div>
<div class="col-md-12 col-12 q-row">
<div class="form-group" [ngClass]="{'has-error':!complexForm.controls['name'].valid && complexForm.controls['name'].touched}">
<input class="form-control" type="text" [formControl]="complexForm.controls['name']">
<div *ngIf="complexForm.controls['name'].hasError('required') && complexForm.controls['name'].touched" class="invalid">Please provide your name.</div>
</div>
</div>
</div>
<input type="file" (change)="fileChanged($event)" name="file1" [formControl]="complexForm.controls['file1']">
<input type="file" (change)="fileChanged($event)" name="file2" [formControl]="complexForm.controls['file2']">
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">Submit</button>
</div>
</form>
this my .ts file
complexForm : FormGroup;
constructor(fb: FormBuilder){
this.complexForm = fb.group({
'name': [],
'file1':[],
'file2':[]
});
}
fileChanged(e: Event) {
debugger;
var target: HTMLInputElement = e.target as HTMLInputElement;
for(var i=0;i < target.files.length; i++) {
this.upload(target.files[i]);
}
}
upload(uploads: File) {
debugger
var formData: FormData = new FormData();
formData.append("files", uploads, uploads.name);
console.log(formData);
}
submitForm(values){
console.log(values);
console.log(FormData);
}
but while selecting file ,upload function is called,but nothing is appending with formData.i want to upload file only after form submission.but some problem with formdata.while consoling it is not showing anything.In formbuild also it is not showing.so any solution for this?thanks in advance.
First of all, you are calling upload for each file, and inside it you create a new instance of FormData. This means that even if you try to submit this form it will only contain the last of the files.
Secondly, you have no reference to that FormData instance you want to submit, because it is created var formData: FormData = new FormData(); inside the scope of the upload function. So, it is not available inside the submitForm function. What you are trying to log there is the Object prototype for FormData, and it would not contain any useful information.
In order to try again you need to refactor your code :
complexForm : FormGroup;
// Declare the object here
private formData: FormData = new FormData();
constructor(fb: FormBuilder){
this.complexForm = fb.group({
'name': [],
'file1':[],
'file2':[]
});
}
fileChanged(e: Event) {
debugger;
var target: HTMLInputElement = e.target as HTMLInputElement;
for(var i=0;i < target.files.length; i++) {
this.upload(target.files[i]);
}
}
upload(uploads: File) {
debugger
// now reference the instance
this.formData.append('file', uploads, uploads.name);
console.log(formData);
}
submitForm(values){
console.log(values);
// Check the formData instance
console.log(this.formData);
}

Acces a file in a file upload input [duplicate]

I actually have a file input and I would like to retrieve the Base64 data of the file.
I tried:
$('input#myInput')[0].files[0]
to retrieve the data. But it only provides the name, the length, the content type but not the data itself.
I actually need these data to send them to Amazon S3
I already test the API and when I send the data through html form with encode type "multipart/form-data" it works.
I use this plugin : http://jasny.github.com/bootstrap/javascript.html#fileupload
And this plugins gives me a preview of the picture and I retrieve data in the src attribute of the image preview. But when I send these data to S3 it does not work. I maybe need to encode the data like "multipart/form-data" but I don't know why.
Is there a way to retrieve these data without using an html form?
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
I created a form data object and appended the file:
var form = new FormData();
form.append("video", $("#fileInput")[0].files[0]);
and i got:
------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv
in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla
Html:
<input type="file" name="input-file" id="input-file">
jQuery:
var fileToUpload = $('#input-file').prop('files')[0];
We want to get first element only, because prop('files') returns array.
input element, of type file
<input id="fileInput" type="file" />
On your input change use the FileReader object and read your input file property:
$('#fileInput').on('change', function () {
var fileReader = new FileReader();
fileReader.onload = function () {
var data = fileReader.result; // data <-- in this var you have the file data in Base64 format
};
fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});
FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)
FileReader API with jQuery, simple example.
( function ( $ ) {
// Add click event handler to button
$( '#load-file' ).click( function () {
if ( ! window.FileReader ) {
return alert( 'FileReader API is not supported by your browser.' );
}
var $i = $( '#file' ), // Put file input ID here
input = $i[0]; // Getting the element from jQuery
if ( input.files && input.files[0] ) {
file = input.files[0]; // The file
fr = new FileReader(); // FileReader instance
fr.onload = function () {
// Do stuff on onload, use fr.result for contents of file
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )
};
//fr.readAsText( file );
fr.readAsDataURL( file );
} else {
// Handle errors here
alert( "File not selected or browser incompatible." )
}
} );
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" />
<input type='button' id='load-file' value='Load'>
<div id="file-content"></div>
To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);
Get file using jquery
element html:
<input id="fileInput" type="file" />
jquery code:
$("#fileInput")[0].files[0]
this work for me :)
HTML
<div class="row form-group my-2">
<div class="col-12">
<div class="">
<div class="text-center">
<label for="inpImage" class="m-2 pointer">
<img src="src/img/no-image.jpg" id="img-visor" height="120" class="rounded mx-auto d-block">
</label>
<input type="file" class="visually-hidden" accept="image/*" name="picture" id="inpImage">
</div>
</div>
</div>
</div>
jQuery
$('#inpImage').change(()=>{
const file = $('#inpImage').prop("files")[0];
const imagen = URL.createObjectURL(file);
console.log(URL.createObjectURL(file));
$('#img-visor').attr('src', imagen);
});
<script src="~/fileupload/fileinput.min.js"></script>
<link href="~/fileupload/fileinput.min.css" rel="stylesheet" />
Download above files named fileinput add the path i your index page.
<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"
`enter code here`accept=".pdf" multiple>
</div>
<script>
$("#uploadFile1").fileinput({
autoReplace: true,
maxFileCount: 5
});
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>

Categories

Resources