Unable implement a functionality to upload multiple images to the server - javascript

Currently, I have the following code that will allow me to upload only one image to the server at the time.
But what I want to do is to upload multiple images. I don't mind if it will send multiple request to the server, but I want to replace the following code, so that I can drag and drop or select multiple images at a time and send it with ajax. How will I be able to achieve this ?
I tried to use some libraries that I found on the web such as dropzone.js, but it seems like it doesnt do the trick. Some simple samples or tips would be great ! I would love to hear from you !
HTML code
<div>
<input type="file" name="mydata[]"/>
<span class="btn" onclick="imgToMyServer('$(this));">Fly Me to the Server ! </span>
</div>
JS side
<script>
function imgToMyServer(ob) {
var form = $('<form />');
var files = ob.prev('input[type="file"]');
var simplefile = files.prop('files')[0];
var Myname = simplefile.name;
var input = $('<input name="mydata[][my_path]" value="path/' + Myname+ '"/>');
switch (simplefile.type) {
case "image/jpeg":
break;
case "image/png":
break;
case "image/gif":
break;
default:');
return false;
break;
}
files.after(files.clone());
files.appendTo(form);
input.appendTo(form);
datas = new FormData(form[0]);
$.ajax({
type: 'post',
processData: false,
contentType: false,
data: datas,
url: "https//www.sample.com/uploads_my_images",
async: true,
success: function (res) {
//Just happy
}
});
}
</script>

What you need its quite simple first you need to add the multiple attribute on the file input type so that it allows you to select multiple files.
Then you need to check the number of images that are selected, then loop through the array of images that are selected then append the images dynamically to the form data :
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div>
<input type="file" name="mydata[]" id ="multiFiles" multiple="multiple">
<button id="upload" class="btn">Fly Me to the Server !</button>
<div id="msg"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#upload').on('click', function (e) {
e.preventDefault();
var form_data = new FormData(); //create form data object
var num_files = document.getElementById('multiFiles').files.length;
for (var x = 0; x < num_files; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]); //append the files to the form data object
}
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, could be json,html
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
server :
<?php
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
}
}
}
} else {
echo 'Please choose at least one file';
}
NB: I did not do any validation of the file uploaded, I just uploaded
straight, you need to validate in both the client and the server side.

Related

How to handle input with multiple files using formData (jQuery) and process them in PHP?

I'm new working with files and I want to upload multiple files in this case images using just one input type file but this input isn't inside a form tag, this work when i click on a button
<input type="file" class="form-control" id="imagenArticulo" multiple="multiple">
when my images are selected I press the button and do this
$('#guardarArticulo').click(function(e) {
e.preventDefault();
let imagen = $('#imagenArticulo').prop('files');
console.log(imagen);
let form_data = new FormData();
form_data.append('imagen', imagen);
$.ajax({
type: 'post',
cache: false,
contentType: false,
processData: false,
url: '../includes/productos/guardar_producto.php',
data: form_data,
dataType: 'json',
beforeSend: function() {
},
success: function(respuesta) {
console.log(respuesta);
if (respuesta.tipo == 0) {
window.location.reload(true);
}
if (respuesta.tipo == 1) {
//do soemthing
}
}
});
});
The first console.log of the variable imagenafter click show this
And finally with PHP when try to process them I do this
if (!is_null($_FILES['imagen']['name'])) {
if ($_FILES['file']['error'] == 0) {
if (!is_dir($ruta)) {
mkdir($ruta);
mkdir($ruta . '/original');
mkdir($ruta . '/thumbnail');
}
$numero_de_imagenes = count($_FILES['imagen']['tmp_name']);
for ($i = 0; $i < $numero_de_imagenes; $i++) {
$imagen = $_FILES['imagen']['name'][$i];
$img_tmp = $_FILES['imagen']['tmp_name'][$i];
$formato = strtolower(pathinfo($imagen, PATHINFO_EXTENSION));
if (in_array($formato, $formatos_validos)) {
$ext_tmp = explode('.', $imagen);
$imagen = sha1($imagen.$random) . '.' . end($ext_tmp);
$ruta = $ruta . '/original/' . $imagen;
move_uploaded_file($img_tmp, $ruta);
list($ancho, $alto) = getimagesize($ruta);
if ($_FILES['imagen']['size'][$i] > 524288 || $ancho > 500 || $alto > 500) {
comprimir($imagen, $fuente, $fuente, 500, 500, 90);
}
comprimir($imagen, $fuente, $destino, 100, 100, 90);
}
}
}
}
I have been with this code before but just for one file, the new part was add the for loop to it, but when i press click the ajax response is not showing nothing, is not displaying errors or something, I would like to know what i'm missing or doing wrong, algo before the code I tried to print $_FILES['imagen'] to see if it has content but dont show nothing, I hope you can help me, thanks.

File uploade with additional Data (Javascript, PHP)

I want to uploade a file and send additional data (an array) to the php script.
Here is the HTML and the Javascript Code:
<input type="file" name="fileinput" id="fileinput">
<button class="btn btn-primary" id="btnupload">upload</button>
<script>
$('#btnupload').click(function(){
var formData = new FormData();
formData.append("MacsToChangeImage", selectedMACs.toString()); //selectedMACs is the array which i want to send
formData.append("userfile", $('#fileinput').files[0]);
$.ajax({
url: "ChangeImagesFunction.php",
type:'POST',
data: formData,
processData: false,
cententType: false,
success: function(data)
{
alert('success' + data);
},
error:function(response){
alert(JSON.stringify(response));
}
});
});
</script>
And here ist the PHP Code:
if(!empty($_FILES)) {
$target_dir = "img/epd_uploads/";
$temporaryFile = $_FILES['userfile']['tmp_name'];
$targetFile = $target_dir . $_FILES['userfile']['name'];
if(!move_uploaded_file($temporaryFile,$targetFile)) {
echo "Error occurred while uploading the file to server!";
}else{
if (isset($_POST['MacsToChangeImage'])){
//Name of the Uploaded File
$ChangeImageToPHP = $_FILES['userfile']['name'];
//Get the Array
$MacsToChangeImageStr = $_POST['MacsToChangeImage'];
$MacsToChangeImagePHP = explode(",",$MacsToChangeImageStr);
}
}
}
I think the HTML and Javascript part is fine so far. But i am uncertain how to handle the PHP part. What am i doing worng/missing?
Are there other ways to achieve what im plannig to do?
Thank you in advance

File upload not working in PHP , $_POST['file'] , not able to extract file

I have the following HTML code:
<form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
<div class="input-wrpr">
<input type="file" name="files[]">
</div>
<button type="submit">
Send File
</button>
</form>
And then the following file upload code in jQuery:
$(function () {
let files = null;
$('input[type="file"]').on('change' , (e) => {
files = e.target.files;
});
$('form').submit(function(e){
e.stopPropagation();
e.preventDefault();
let data = new FormData();
// files = $('input[type="file"]')[0].files;
$.each(files, function(key, value){
data.append(key, value);
});
console.log(data.getAll('0'));
// console.log(data);
$.ajax({
type: $(this).attr('method'),
url : $(this).attr('action'),
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data : data
}).done(function(data){
// console.log(data);
if (! data.success) {
// console.log(data.errors);
/*for(let er in data.errors) {
console.log(data.errors[er])
}*/
console.log(data);
} else {
/* else condition fires if form submission is successful ! */
console.log(data.file);
}
}).fail(function(data){
console.log(data);
});
});
});
And the following PHP code for testing :
<?php
// You need to add server side validation and better error handling here
$data = array();
if(isset($_FILES['files'])) {
$data = array('file' => 'I a in if');
}
else {
$data = array('file' => 'I am in else');
}
echo json_encode($data);
?>
Now when i check my console i see that the PHP if condition is not passing , that is it is unable to detect:
isset($_POST['files'])
Why is this happening ? I have tried using isset($_FILES['files']), also I have tried renaming my html file input field to just files instead of files[] , but this does't seem to work , What am I doing wrong ?
I was following the tutorial HERE. But somehow the example I have created just does't work.
Try to print_r($_FILES) and check if it shows an array of file,
If it does, use the same key in $_FILES['same_key_here'] and it supposed to work,
Let me know if it doesn't
If you want to send files, do something like this.
This may help you.
var fileInput = $("#upload_img")[0]; // id of your file
var formData = new FormData();
formData.append("image_file",fileInput.files[0]); //'xmlfile' will be your key
Check in your php code like,
echo $_POST['image_file'];

How do I send images in an ajax request? [duplicate]

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

No file being uploaded while uploading multiple files using AJAX

I am trying to upload multiple files with only 1 AJAX request. But I am facing some problems and they are:
UPDATE
No file is being uploaded to the server
It seems to me that multiple AJAX requests are being made as AJAX is inside the for loop.
How to sort these problems?
HTML
<!--<form id="fileupload" method="POST" enctype="multipart/form-data">-->
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
<!--</form>-->
JS
$("#uploadfile").change(function(){
//submit the form here
//$('#fileupload').submit();
var files = $("#uploadfile")[0].files;
for (var i = 0; i < files.length; i++){
//alert(files[i].name);
var data = files[i].name;
$.ajax({
type:'POST',
url: 'mupld.php',
data: data
});
}
//var files = $('#uploadfile').prop("files"); //files will be a FileList object.
//alert(files);
//var names = $.map(files, function(val) { return val.name; }); //names is an array of strings (file names)
});
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
js at Question does not appear to upload File object, but File.name at var data = files[i].name; ? <!-- --> is not valid comment in javascript
Try using FormData()
$("#uploadfile").change(function() {
var files = $("#fileupload")[0];
$.ajax({
type:"POST",
url: "mupld.php",
data: new FormData(files),
processData: false,
contentType: false
});
});
Use it
AJAX File Upload plugin
<pre>
$("#uploadfile").change(function(){
$.ajaxFileUpload
(
{
url:'mupld.php',
secureuri:false,
fileElementId:'uploadfile[]',
dataType: 'html',
data:{},
success: function (data, status)
{
},
error: function (data, status, e)
{
}
}
);
});
</pre>

Categories