从 NodeJS 上传多张图片到 PHP 服务器

NodeJS 开发人员,我有一种情况,我必须将本地图像从 NodeJS 上传到 PHP 服务器。没有报错,请求成功 200 OK,但是图片没有出现在PHP服务器中。


注意:我是一名 nodeJS 开发人员,在 PHP 方面没有太多经验。


这是想做的事情:


在 NodeJs 中,有一个文件列表,现在我想将这些文件一个一个地附加到 formData 中,之后,我必须将这个表单数据发布到 PHP 服务器,以便将图片上传到 PHP 服务器,


在 PHP 服务器中,在第一行,它从 post 请求接收文件,然后循环将具有支持扩展名的文件一个一个地移动到上传目录,循环完成后它发回一个包含文件数组的响应'下载地址


一切正常,我已经安慰了一切,一切都有完美的价值,甚至 HTTPS POST 请求也成功了,但是 PHP 服务器没有图像,PHP 服务器没有接收请求中的文件,所以看起来多部分数据不起作用NodeJs。


看起来 formData 在 NodeJs 中不能正常工作,因为相同的代码在浏览器中的客户端 JS 上工作。


节点:-


 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',formData,

     {

         headers: formData.getHeaders()

     })

     .then(d => console.log("DONE=>>>> ", d.data))

     .catch((f) => console.log('FAILED=>> ', f))


    });

PHP 代码:-


<?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;


宝慕林4294392
浏览 201回答 5
5回答

海绵宝宝撒

<?php// Count total filesvar_dump($_FILES['files']);$countfiles = count($_FILES['files']['name']);echo $countfiles;// Upload directory$upload_location = "uploads/";// To store uploaded files path$files_arr = array();// Loop all filesfor($index = 0;$index < $countfiles;$index++){&nbsp; echo $index;&nbsp; &nbsp;// File name&nbsp; $filename = $_FILES['files']['name'][$index];&nbsp; echo $filename;&nbsp; &nbsp;// Get extension&nbsp; $ext = pathinfo($filename, PATHINFO_EXTENSION);&nbsp; echo $ext;&nbsp; &nbsp;// Valid image extension&nbsp; &nbsp;$valid_ext = array("png","jpeg","jpg", "csv");&nbsp; &nbsp;// Check extension&nbsp; &nbsp;if(in_array($ext, $valid_ext)){&nbsp; &nbsp; &nbsp;// File path&nbsp; &nbsp; &nbsp;$path = $upload_location.$filename;&nbsp; &nbsp; &nbsp;// Upload file&nbsp; &nbsp; &nbsp;if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){&nbsp; &nbsp; &nbsp; &nbsp; $files_arr[] = $path;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}}/* echo json_encode($files_arr); */die;const Axios = require('axios');&nbsp;const Fs = require('fs');&nbsp;const FormData = require('form-data');const allFiles = [&nbsp; {uri: 'my/Spark_Dataset/combin.csv'},&nbsp; {uri: 'my/Spark_Dataset/combine-csv.csv'},&nbsp; // {uri: 'C:\\Users\\my\\combine-csv.csv'}];(async function() {&nbsp; var formData = new FormData();&nbsp; //here allFiles is an array of object , each object contains 1 file with details like local file path ,name,size&nbsp; for (var index = 0; index < allFiles.length; index++) { //Append multiple files to formData.&nbsp; &nbsp; // console.log(index);&nbsp; &nbsp; let currentFile = allFiles[index]&nbsp; &nbsp; //createReadStream Retyrns fileData&nbsp; &nbsp; // console.log(currentFile);&nbsp; &nbsp; let fileWithInfo = await Fs.createReadStream(currentFile.uri)&nbsp; &nbsp; formData.append("files[]", fileWithInfo );&nbsp; }&nbsp; console.log(formData);&nbsp; Axios.post('http://localhost:8000/upload.php',&nbsp; &nbsp; formData,&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; headers: formData.getHeaders(),&nbsp; &nbsp; &nbsp; // 'Content-Type':'multipart/form-data',&nbsp; &nbsp; })&nbsp; &nbsp; .then(d => console.log("DONE=>>>> ", d.data))&nbsp; &nbsp; .catch((f) => console.log('FAILED=>> ', f))})();packages.json"axios": "^0.20.0","form-data": "^3.0.0","fs": "0.0.1-security",首先我启动了本地服务器php -S localhost:8000运行本地服务器后,我运行 index.js 文件,node index.js我在本地测试了代码,它工作正常。

慕标5832272

Axios.post('example.com/upload.php', formData, {&nbsp; headers: formData.getHeaders()}).then(d => console.log("DONE=>>>> ", d.data)).catch((f) => console.log('FAILED=>> ', f));您缺少axios post 请求中您的情况,您可以直接传递 formData 或调用 formData.getBuffer() data。formData

慕莱坞森

https://github.com/form-data/form-data#buffer-getbufferconst { readFile } = require('fs/promises');for (let index = 0; index < allFiles.length; index++) {&nbsp; const currentFile = allFiles[index];&nbsp; const fileWithInfo = await readFile(currentFile.uri);&nbsp; formData.append('files[]', fileWithInfo);}axios.post('https://example.com/', formData.getBuffer(), formData.getHeaders());// you have to send files as buffer还有流 https://stackoverflow.com/a/53126159/8784402的解决方案const response = await axios({&nbsp; &nbsp; &nbsp; &nbsp; method: 'post',&nbsp; &nbsp; &nbsp; &nbsp; url: 'http://www.yourserver.com/upload',&nbsp; &nbsp; &nbsp; &nbsp; data: formData,&nbsp; &nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; 'content-type': `multipart/form-data; boundary=${form._boundary}`,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; });

泛舟湖上清波郎朗

也许我的回答没有解决,但我建议对 PHP 代码进行一些更改。当然,$_FILES 数组中的键不能是数字,最好使用 foreach 而不是 for。我允许自己稍微更改您的代码以使其更小<?php// Upload directory$upload_location = "uploads/";// To store uploaded files path$files_arr = array();// Valid image extension$valid_ext = array("png","jpeg","jpg");foreach($_FILES['files']['name'] as $key => $file) {&nbsp; &nbsp; if(&nbsp; &nbsp; &nbsp; &nbsp; in_array(pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION), $valid_ext)&nbsp; &nbsp; &nbsp; &nbsp; &&&nbsp; &nbsp; &nbsp; &nbsp; move_uploaded_file($_FILES['files']['tmp_name'][$key],$upload_location.$_FILES['files']['name'][$key])&nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; &nbsp; $files_arr[] = $upload_location.$_FILES['files']['name'][$key];&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; //Only for debugging&nbsp; &nbsp; &nbsp; &nbsp; $files_arr[] = 'Not uploaded: '.$upload_location.$_FILES['files']['name'][$key];&nbsp; &nbsp; }}echo json_encode($files_arr);die;

慕桂英3389331

您allFiles.length在 NodeJS 代码中错过了循环中的参数。正确的代码将是for&nbsp;(var&nbsp;index&nbsp;=&nbsp;0;&nbsp;index&nbsp;<&nbsp;allFiles.length;&nbsp;index++)&nbsp;{PHP代码是正确的,但是如果你发送一个空的files数组,它不会出错并且会返回成功响应!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript