how to upload all images from a folder - javascript

trying to upload all images from a folder
destination folder on server side is test
destination format for images is uniqid().jpg
problem - seems resulting array on server side is empty
<input type='file' class='inpfile' id='inpfo' webkitdirectory='' directory='' multiple='true'>
var inpfo = $('#inpfo');
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
fd.append('flist', flist);
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
contentType: 'multipart/form-data',
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
upload.php
$arr = $_FILES['flist']; //seems this is an empty array
foreach($arr as $el){
$tempname = $el['tmp_name'];
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}

You are passing a FileList object fd.append which is incorrect you have to loop through the list and add each file individually.
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
for (let i = 0; i < flist.length; i++){
fd.append('flist[]', flist[i]); // add [] to denote array
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
You're using the array of files incorrect, see here
$arr = $_FILES['flist'];
foreach($arr['tmp_name'] as $tempname){
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}

Related

Ajax request does not send blob data

I want to send data using an Ajax request to PHP.
I have the following data in my formData variable:
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
Printing the form entries gives me this:
I do the request like this:
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
In post.php I print the recieved data:
print_r("First name: " . $_POST["fname"] . PHP_EOL);
print_r("Last name: " . $_POST["lname"] . PHP_EOL);
print_r("Email: " . $_POST["email"] . PHP_EOL);
print_r("Data: " . $_POST["data"] . PHP_EOL);
For some reason it does not receive the 'data' entry in the $_POST variable. I get the following notice: "Notice: Undefined index: data"
Why does that happen? Could I somehow send the blob information?
As requested, the whole code. (inputFname, inputLname and inputEmail are not null. The code is situated inside a button onclick event method.
let evtTgt = e.target;
const container = evtTgt.parentNode;
const audioElement = container.getElementsByTagName("audio")[0];
const audioURL = audioElement.src;
let newBlob = await fetch(audioURL).then(result => result.blob());
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
for (var key of formData.entries()) {
console.log(key[1]);
}
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
All this time I was looking for the blob contents inside the $_POST variable. I should have looked in the $_FILES variable instead!
I managed to get the file contents by calling this inside the php script:
$fileinfo = file_get_contents($_FILES['data']['tmp_name']);

Send FormData and string using one function

I want to send data from the form (file from input and string from input) using ajax to ASP.NET Function. If I send only files i use:
function readURL() {
var input = document.getElementById("fileUpload");
var files = input.files;
var formData = new FormData();
var test = "some text";
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: {files: formData },
processData: false,
contentType: false,
});
}
If I want to send an only string, I use:
function readURL() {
var input = document.getElementById("fileUpload");
var files = input.files;
var formData = new FormData();
var test = "some text";
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: { test: test},
dataType: "json",
});
}
It is possible to send string and FormData using one Ajax? I try something like this:
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: {files: formData, test: test },
processData: false,
contentType: false,
});
but now the string parameter is not sending (is null).
Additional - My Controller code
public async Task<IActionResult> UploadFiles(string test, IList<IFormFile> files)
{
...
}
It's not possible to combine multiple Content Types when sending a FormData object.
Append the string to the formData instance and set the name to test.
function readURL() {
var input = document.getElementById("fileUpload");
var files = input.files;
var formData = new FormData();
var test = "some text";
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
formData.append("test", test);
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: formData,
dataType: "json",
processData: false,
contentType: false,
});
}

Form data not being retrieved by handler after it is sent

I'm trying to send an image to an ajax handler via ajax. If I console.log the variable ìmage I am sending, it looks fine. As of now I am sending it to the handler and just trying to echo it back. But I get a blank response. I am sending the image: formData inside an object which I hope is ok.
Ajax:
var form_data = new FormData();
var image = $('#newImage').prop('files')[0];
var image_name = image.name;
var image_extension = image.name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension, ['gif', 'jpg', 'JPG', 'pjpeg', 'x-png', 'png', 'PNG', 'jpeg']) == -1) {
alert("Invalid Image File Type")
}
var image_size = image.size;
if(image_size > 700000) {
alert("Image too big!");
} else {
form_data.append('file', image);
}
let data = {
action: 'NewEventExhibition',
name: name,
description: description,
notes: notes,
status: status,
slug: slug,
start_date: start_date,
end_date: end_date,
event_code: '<?=$code?>',
image: form_data
};
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false,
mimeType: 'multipart/form-data',
success: function(response) {
alert(response);
},
fail: function(response) {
console.log(response);
}
})
}
});
Handler
if($_FILES['file']['name'] != '') {
$test = explode(".", $_FILES['file']['name']);
$extension = end($test);
$name = rand(100, 999).'.'.$extension;
$location = "/assets/images/".$name."";
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo $location;
}
```
That's not how you send a FormData object with ajax. The form_data object should be the thing that you send, not it being part of a bigger object.
I would recommend you to append all the fields of the object data to the form_data and send it.
Something like the following:
form_data.append('action', 'NewEventExhibition');
form_data.append('name', name);
form_data.append('description', description);
form_data.append('notes', notes);
form_data.append('status', status);
form_data.append('slug', slug);
form_data.append('start_date', start_date);
form_data.append('end_date', end_date);
form_data.append('event_code', '<?=$code?>');
instead of let data = { .... }.
Then you can send it with
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: 'multipart/form-data',
success: function(response) {
alert(response);
},
fail: function(response) {
console.log(response);
}
});
Please note the data: form_data.

Google Drive API multipart upload gets file corrupted, size 1kb

I've been trying to upload a file using the Google Drive API but I'm facing this issue and I can't seem to find the solution. When uploading an image, it uploads a corrupted file of size 1kb with correct metadata and while uploading text files, it uploads a text file with [object file] as data and not the original data of the file.
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var control = document.getElementById("csv");
var files = control.files;
var dat=files[0];
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
contentType: false,
data: "\n--foo_bar_baz\ \nContent-Type: application/json; charset=UTF-8\ \n\n{ 'name': '"+dat.name+"' }\ \n--foo_bar_baz\ \nContent-Type: "+dat.type+"\ \nContent-Transfer-Encoding: base64\ \n\n"+dat+"\ \n--foo_bar_baz--\ ",
headers: {
"Authorization":"Bearer <?php echo $result["access_token"]; ?>",
"Content-Type": "multipart/related; boundary=foo_bar_baz",
"Content-Length": formData.length
},
async: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
var res = JSON.stringify(response);
console.log("S: "+res);
},
error: function(response) {
var res = JSON.stringify(response);
console.log("E: "+res);
}
});
return false;
});
How about this answer? Please think of this as just one of several possible answers.
Modification points:
You are trying to upload the file as base64. But in your script, dat is not base64.
In this case, I used FileReader.
Please remove \ of \ \n in "\n--foo_bar_baz\ \nContent-Type: application/json; charset=UTF-8\ \n\n{ 'name': '"+dat.name+"' }\ \n--foo_bar_baz\ \nContent-Type: "+dat.type+"\ \nContent-Transfer-Encoding: base64\ \n\n"+dat+"\ \n--foo_bar_baz--\ ",.
When above points are reflected to your script, it becomes as follows.
Modified script:
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var control = document.getElementById("csv");
var files = control.files;
var dat = files[0];
var f = new FileReader(); // Added
f.onload = function(){ // Added
const base64Data = this.result.split(",")[1]; // Added
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
contentType: false,
data: "\n--foo_bar_baz\nContent-Type: application/json; charset=UTF-8\n\n{'name': '"+dat.name+"'}\n--foo_bar_baz\nContent-Type: "+dat.type+"\nContent-Transfer-Encoding: base64\n\n"+base64Data+"\n--foo_bar_baz--\n", // Modified
headers: {
"Authorization": "Bearer <?php echo $result["access_token"]; ?>",
"Content-Type": "multipart/related; boundary=foo_bar_baz",
"Content-Length": formData.length
},
async: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
var res = JSON.stringify(response);
console.log("S: "+res);
},
error: function(response) {
var res = JSON.stringify(response);
console.log("E: "+res);
}
});
}
f.readAsDataURL(dat); // Added
return false;
});
Note:
When uploadType=multipart is used, the maximum file size is 5 MB. Please be careful this. Ref
If this was not the direct solution of your issue, I apologize.

jQuery - DataTables upload file using ajax

I am using the plugin datatable to show a list of users. In this list I need to be able to upload new files.
I am trying to use ajax to try to send data to php. If I send value there is not problem my php script works however, I cannot get the data from the files.
In order to upload the files I am using the same script that I have written for another project which is working fine, so I think here the problem is DataTable that do not recognise my form data.
Anyone knows how to achieve this?
FIDDLE
JS
$('#example .fileinput-upload-button').on('click', function(event) {
var td = $(this).closest("td");
var parentTD = td.parent();
var form = $(this).closest("form");
var url = "example/upload.php?type=photo"
var data = new FormData(form);
alert(form);
$.ajax({
type: "POST",
url: url,
data: data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType: "html",
processData: false,
success: function(data) {
alert(data);
}
});
PHP
$type = filter_input(INPUT_GET, "type");
$target_dir_header = $includesDir . "dashboard/resources/header_pic/";
$dataHeader = $_FILES['input7'];
$dataHeader_ext = explode('/', $dataHeader['type']);
$imageFileType_header = $dataHeader_ext[1];
$target_file_header = $target_dir_header . basename("header" . $imageFileType_header);
echo $type . " - " . $imageFileType_header;
Change your JQuery code to:
var td = $(this).closest("td");
var parentTD = td.parent();
var url = "example/upload.php?type=photo"
var form = $(this).closest("form").get(0);
$.ajax({
type: "POST",
url: url,
data: new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType: "html",
processData: false,
success: function(data) {
alert(data);
}
});
Your question explains here

Categories

Resources