Sunday 18 October 2020

UPLOAD MULTIPLE IMAGES FROM NODEJS TO PHP SERVER

NodeJS devs, I have a situation where I have to upload local images from NodeJS to PHP Server. There's no error, the request is successful 200 OK, but the picture does not appear in the PHP server.

Note: I am a nodeJS developer, don't have much experience in PHP.

Here's what wanna do:

In NodeJs, there's a list of files, Now one by one I want to append these files into formData, after that, I have to post this form data to the PHP server so that the pictures are uploaded to the PHP server,

In PHP server, at the first line, it is receiving the files from the post request and then with loop moving files with supported extension one by one to the upload directory and after the loop completes it sends back a response with an array containing files' download URL

Everything is working, I've consoled everything and everything has the perfect values and even the HTTPS POST request is successful but the PHP server there is no images, PHP server is not receiving files in the request so looks like multipart data is not working in NodeJs.

Looks like formData is not working properly in NodeJs because the same code works on client JS in the browser.

NodeJS:-

 const Axios = require('axios');
 const Fs = require('fs');
 const FormData = require('form-data');



 var formData = new FormData();

 //here allFiles is an array of object , each object contains 1 file with details like local file path ,name,size
for (var index = 0; index < allFiles.length; index++) { //Append multiple files to formData.

            let currentFile = allFiles[index]
            //createReadStream Retyrns fileData
            let fileWithInfo = await Fs.createReadStream(currentFile.uri)
            formData.append("files[]", fileWithInfo );

       }
 Axios.post('example.com/upload.php',
     {
         headers: formData.getHeaders()
     })
     .then(d => console.log("DONE=>>>> ", d.data))
     .catch((f) => console.log('FAILED=>> ', f))

    });

PHP CODE:-

<?php
// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$upload_location = "uploads/";

// To store uploaded files path
$files_arr = array();

// Loop all files
for($index = 0;$index < $countfiles;$index++){

   // File name
   $filename = $_FILES['files']['name'][$index];

   // Get extension
   $ext = pathinfo($filename, PATHINFO_EXTENSION);

   // Valid image extension
   $valid_ext = array("png","jpeg","jpg");

   // Check extension
   if(in_array($ext, $valid_ext)){

     // File path
     $path = $upload_location.$filename;

     // Upload file
     if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
        $files_arr[] = $path;
     }
   }

}

echo json_encode($files_arr);
die;



from UPLOAD MULTIPLE IMAGES FROM NODEJS TO PHP SERVER

No comments:

Post a Comment