php curl 无法一次性上传多个文件
程序员文章站
2022-05-30 20:41:53
...
环境:windows7+xampp
需要实现:php curl模拟form表单上传多个文件,后端nodejs(express+multer)接收请求+保存文件
出现情况:单文件上传可行,多文件报错
版本:php 5.6+nodejs 6.11.4
function curl_upload($url, $timeout = 1000) {
$ch = curl_init();
$data = array(
'upload' => curl_file_create('E:\www\vhost.php', 'text/html', 'ph')
);
//兼容5.0-5.6版本的curl
if (class_exists('\CURLFile')) {
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, FALSE);
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
var fs = require('fs')
var express = require('express')
var multer = require('multer')
const path = require('path');
var app = express();
var upload = multer({
dest: 'upload/'
});
//多文件上传 (限定上传文件个数)(没有修改后缀)
app.post('/upload-multi', upload.array('upload', 3), function(req, res, next) {
var file = req;
console.log(file);
})
上述方法Nodejs可以接收并保存单文件。
变成多文件后:
function curl_upload($url, $timeout = 1000) {
$ch = curl_init();
$data = array(
'upload[0]' => curl_file_create('E:\www\vhost.php', 'text/html', 'ph'),
'upload[1]' => curl_file_create('E:\www\ser.php', 'text/html', 'ser')
);
//兼容5.0-5.6版本的curl
if (class_exists('\CURLFile')) {
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, FALSE);
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
}
nodejs报如下错误:
如下:使用正常的表单上传多文件,nodejs能正常接收
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<form id="upload-form" action="http://127.0.0.1:7777/upload-multi" method="post" enctype="multipart/form-data">
<input type="file" name="upload" /> <br />
<input type="file" name="upload" /> <br />
<input id="bbb" type="submit" value="Upload" />
</form>
</body>
</html>
查了无数文档后,仍然找不到解决方案。