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');
Related
I have a simple form so you can upload images. I store the uploaded images' properties in a array but I want to post this array to a PHP file using ajax. If I try to get the uploaded image: $_FILES['image1'], it returns an empty array. Any idea what I am doing wrong?
PS: It is important to store the images' properties in a array and pass it to a FormData.
var foo = []; var input = document.getElementById('input');
document.getElementById('add').addEventListener('click', () => {
foo.push(input.files[0]);
});
document.getElementById('check').addEventListener('click', () => {
console.log(foo);
});
document.getElementById('upload').addEventListener('click', () => {
var fd = new FormData();
for (let i = 0; i < foo.length; i++) {
fd.append('image'+i, foo[i]);
}
$.ajax({
enctype: "multipart/form-data",
type: "POST",
url: "path/to/php.file",
data: fd,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) { console.log(data); },
error: function (err) { console.log(err); }
});
});
<button id="add">ADD</button>
<button id="check">CHECK</button>
<button id="upload">UPLOAD</button>
<br><br>
<input type="file" id="input" placeholder="UPLOAD IMAGE">
And the PHP file:
<?php
$arr = array();
array_push($arr, $_FILES);
die(json_encode($arr));
?>
Or you need to check php.ini and check if the size of all the images you add exceeds "upload_max_filesize"
I executed the code with two files. It seems that you can print the files successfully with the following code (PHP file)
print_r($_FILES['image0']);
print_r($_FILES['image1']);
I used jquery 3.5.1, for the ajax call.
I hope it helps.
I have this html
<input type="file" name="[]" multiple />
Now I want to upload each of the files separately but I am really stuck.
$('input:file').on('change', function(){
allFiles = $(this)[0].files;
for(var i = 0; allFiles.length > i; i++){
eachFile = allFiles[i];
$.ajax({
url: link,
type: "POST",
data: new FormData(eachFile),
contentType: false,
processData:false,
success: function(result){
console.log(result);
}
})
}
})
But I don't seem to work. I use the above ajax request to upload files in an array but I want to upload them differently. Any suggestion on how to achieve this?
This is not a duplicate to the supposed duplicate question. I want to upload multiple files separately to the server but the question marked wants to upload multiple files at once. I use my above code to upload multiple files to the server at once an it works fine. So why should I as what I already have a solution to?
Use this... Tested (in chrome) and working
$('input:file').on('change', function(){
allFiles = $(this)[0].files;
for(var i = 0; allFiles.length > i; i++){
var eachFile = allFiles[i],
fileData = new FormData();
fileData.append('file', eachFile);
$.ajax({
url: link,
type: "POST",
datatype:'script',
data: fileData,
contentType: false,
processData:false,
success: function(result){
console.log(result);
}
})
}
})
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.
I have 2 forms:
Form A contains field name, age, address, email and a hidden text field for the names of images which are going to be uploaded in form B.
Form B contain an input type File so users can browse and select their photos.
I used Jquery to trigger an function upload those images after they are selected.
I'm stuck at the step passing the selected images array to the PHP file that handles upload progress via AJAX.
I searched but there were no samples for my problem. I appreicate any help.
<form action="upload_img.php" name="form_B" method="POST" enctype="multipart/form-data">
Select images: <input type="file" name="selected_imgs[]" id="selected_imgs" multiple>
</form>
<script type="text/javascript">
$(function() {
$("input:file").change(function (){
ajax_upload();
});
});
</script>
You can try below code
function uploadFile(){
var file = $('#filetoupload');
var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.doc|\.xls|\.txt|\.rtf|\.pdf)$/i;
var isvalid = true;
//for every file...
var input = document.getElementById('filetoupload');
for (var x = 0; x < input.files.length; x++) {
if(!valid_extensions.test(input.files[x].name)){
isvalid = false;
}
}
if(isvalid == true ){
var formData = new FormData();
for (var x = 0; x < input.files.length; x++) {
formData.append("filetoupload[]",input.files[x]);
}
$.ajax({
url: 'localhost/upload.php', //server script to process data
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success:function (data){
alert("File Uploaded");
// data.src return from your server
// so you can display image in page using <img> tag
},
error:function (data){
alert("Error!");
}
});
}else{
alert("File format not supported!");
return false;
}
return true;
}
<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.