How to use dropzone JS for some button on the page? - javascript

I have few buttons on the page. I need to load file when I click on each of buttons.
Every button has unique data-id attribute, which I must to pass in request AJAX, when I click it.
How can I do this using Dropzone plugin?

As requested, here is an example of how you can create a button that will upload a file and a data attribute with Bootstrap.
<button class='btn btn-default chooser' data-id='hello'>Choose a file</button>
The JS requires this helper library I wrote for this exact purpose: fileUpload.js
$(".chooser").each(function() {
var ele = this;
$(ele).fileUpload({
change: function() {
// Get the files from the input
var files = $(ele).fileUpload("getFiles");
var formData = new FormData();
for (var i = files.length; i--;)
formData.append('myFiles[]', self.files[i], self.files[i].name);
// Get the data attribute from the button
formData.append('data-id', $(ele).data('id'));
$.ajax({
url: "http://mywebsite.com/uploads",
type: 'POST',
data: formData,
processData: false,
contentType: false,
}).always(function(xhr) {
// all done. do something with the response here
});
}
});
});
There are other options, you can restrict it to only accept certain file types or multiple files, etc. See the link above for more info.

Related

Saving images uploaded using ImagesLoader

I am trying to wire up the ImagesLoader plugin, which allows uploading multiple images. It has a nice drag-n-drop UI but I just can't figure out how to get the images that were uploaded. I cannot find any documentation.
Link to the plugin page: ImagesLoader
Here is the javascript from the demo:
<script type="text/javascript">
// Ready
$(document).ready(function () {
// Create image loader plugin
var imagesloader = $('[data-type=imagesloader]').imagesloader({
minSelect: 3
,imagesToLoad: [{"Url":"./img/Nespresso001.jpg","Name":"Nespresso001"},{"Url":"./img/Nespresso002.jpg","Name":"Nespresso002"}]
});
//Form
$frm = $('#frm');
// Form submit
$frm.submit(function (e) {
var $form = $(this);
var files = imagesloader.data('format.imagesloader').AttachmentArray;
var il = imagesloader.data('format.imagesloader');
if (il.CheckValidity())
alert('Upload ' + files.length + ' files');
e.preventDefault();
e.stopPropagation();
});
});
The images are saved in the object "files". Here is a screen shot of the contents from the inspector:
I tried converting to json and posting, but that only generates an error.
$.ajax({
url: 'process-images.php',
type: 'POST',
data: JSON.stringify(files),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
error: function() {alert("ERROR");},
success: function() {alert("OK");}
});
The rest of the code works just like the demo. Looks like everything needed for the uploaded images is stored in "files". I just need to get the data back to php and I can pull it apart from there. But right now, the original submit code just dies or my addition aborts with an error.
THANKS!
I hope it is not too late to answer.
You just need to loop through the base64 encoded image object, decoding and saving each image to the disk.
// Sample code
foreach(json_decode($request->input('files')) as $file) {
$name = $file->FileName
$imagePath = storage_path('app/public/images/');
file_put_contents($imagePath.$name, base64_decode($file->Base64));
}

Upload files when it selected

I am trying to make an input field. I want it when I select files, it automatically uploads them without pressing any upload button. here is my code. not mentioning the CSS because it is irrelevant. but if you need it I'll provide it.
//html
<!-- some codes here-->
<input type="file" id="fileUpload" multiple="true" />
<!-- some codes here-->
//javascript
$(document).ready(() => {
$("#fileUpload").on("change", (e)=>{
var formData = new FormData();
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
formData.append("file[]", files[i]);
}
uploadFormData(formData);
});
function uploadFormData(form_data) {
$.ajax({
url: ".uploader.php",
method: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#filenames").html(data);
$(".alert-container div").removeClass("alert-box alert-err");
$(".alert-container div").addClass("alert-box alert-ok");
$("#alertCheck").prop( "checked", true );
setTimeout(()=>{
$("#alertCheck").prop( "checked", false );
}, 5000);
},
error: function (data) {
$(".alert-container div").removeClass("alert-box alert-ok");
$(".alert-container div").addClass("alert-box alert-err");
console.log("err");
},
});
}
});
The issue is due to the way you're accessing the files collection from the event. The code you're using right now works for custom jQueryUI event handlers, yet you're using a standard change event handler. As such you need to change this line:
var files = e.originalEvent.dataTransfer.files;
To this:
var files = e.target.files;
Does this work?
var files = $("#fileUpload").prop('files');

Appended files to FormData not received at Laravel server

I'm facing a strange issue ... I've a form with multiple fields .. on form submit, I append multiple image files to form data and submit it like this:
$('#newEntry').on('submit', function(e){
e.preventDefault();
const formData = new FormData(e.target);
formData.delete('images[]');
for (var i = 0; i < filesToUpload.length; i++) {
formData.append('images[]', filesToUpload[i].file, filesToUpload[i].file.name);
}
$(this)[0].submit();
});
and when I try to echo(count($request->images)) at Laravel server it echos 0 .. and on dd($request) .. I see empty files array
but when I submit same form with same files directly from input field instead of appending data to it like this:
<input type="file" name="images[]">
I receive all files at server.
Files are successfully appended to formData .. I've checked it by:
var formKeys = formData.keys();
var formEntries = formData.entries();
do {
console.log(formEntries.next().value);
} while (!formKeys.next().done)
I've also tried to send same appended files through AJAX and it worked perfectly fine:
$('#newEntry').on('submit', function(e){
e.preventDefault();
const formData = new FormData(e.target);
formData.delete('images[]');
for (var i = 0; i < filesToUpload.length; i++) {
formData.append('images[]', filesToUpload[i].file, filesToUpload[i].file.name);
}
$.ajax({
url: actionURL,
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("DONE");
},
error: function (data) {
alert("ERROR - " + data.responseText);
}
});
});
on digging down deeper .. I've found that when I submit a form via Http request an Error with code 500 Internal Server Error appears in console for a moment (just before page reloads)
tried everything but don't know what is causing this strange behavior .. kindly help me sort it out
You can check the network tab of your browser(Preferably Chrome) to compare the request parameters that you send to the server.
If the request is too fast that you can't capture it, try placing debugger;(Or click on the in front of the line of code in the source tab) into your Javascript code to stop the execution of the code right before it reload. Then you can inspect the current state of your Javascript and also the 500 response that you received.

Uploading multiple files from different inputs using Ajax

I have two different file inputs and multiple textual/select inputs, that I'd like to upload to a PHP file using Ajax. The file inputs are meant to send images, and because they are two specific images that I'd like to identify by the name of the input, I do not want to use <input type="file" multiple>.
Currently I have the following (names have been changed to keep it simple):
<input type="file" name="file1">
<input type="file" name="file2">
<textarea name="text1"></textarea>
<button>Submit</button>
What I have tried is to push both to a variable once the change event of the file input gets fired, followed by the button press triggering the upload using Ajax.
$('input[type="file"][name="file1"]').on('change', prepareUpload);
$('input[type="file"][name="file2"]').on('change', prepareUpload);
files = new Array;
function prepareUpload(event){
files.push(event.target.files);
}
$('button').on('click', uploadFiles);
function uploadFiles(event){
$('#uploadInfo').html('Uploading...');
event.stopPropagation();
event.preventDefault();
var data = new FormData();
$.each(files, function(key, value){
data.append(key, value);
});
data.append('text1', $('textarea[name="text1"]').val());
$.ajax({
url: '',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
//do stuff
},
error: function(error){
console.log(error);
}
});
}
But this seems to do nothing. Is it even possible to append two image inputs to the same request using Ajax, or am I better off trying to put it in two different requests?
event.target.files is a array, so you need the first file in the array
function prepareUpload(event){
files.push(event.target.files[0]);
}

how to queue file uploading in ajax jquery?

<script>
funcupload(i) {
var formData = new FormData();
files = $("#upload").get(0).files;
formData.append("upfiles[]", files[i]);
$.ajax({
url:"upload.php",
type: 'post',
data: formData,
cache: false,
processData: false,
contentType: false,
success:function(data) {
alert("Complete");
i++;
}
}
</script>
<input type=\"file\" id=\"upload\" name=\"upfiles[]\" multiple>
<input type=\"button\" value=\"Upload\" name=\"upload\" onclick=\"funcupload(0)\">
I want to queue for upload files. In my above code when first file is uploading, second file is pending status. But if upload button clicked again after select files then first file is starting to upload same time with first file added to the previous click of upload button.
How can queue ajax upload for files Or in other words how can added next files to current ajax?
What I think you want to do:
user select 4 files to upload.
User clicks button
you want to do an ajax-call for each file, but they can't overlap
If that's the case, then you can do this:
var filesToUpload = null;
var uploadNextFile(counter)
{
$.ajax({
url:"upload.php",
type: 'post',
data: files[i],
cache: false,
processData: false,
contentType: false,
success:function(data) {
if (counter < filesToUpload.length)
uploadNextFile(counter++);
else
filesToUpload = null;
}
}
}
Now, when the submit-button is clicked, you call uploadNextfile() and pass the files and counter 0.
If the user adds files, you can check if filesToUpload is empty or not. If it's not empty, you can add the files, and the code will continue running:
filesToUpload.push(/*extra files*/);
If it's empty, you can just call the function again.

Categories