我必须将文件发布到远程服务器上的 php api url。我正在创建一个 http.request,然后尝试通过从文件流中通过管道将文件数据写入该请求,如下所示:
var req = http.request( options, function(response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
var fs = require('fs');
var boundaryKey = "5JtsIWpXzRoEIdPqkQiSWv4Tl8Bmq";//Math.random().toString(16); // random string
var filelen = filelen; \\Already calculated before
req.setHeader('Content-Type', 'multipart/form-data;boundary='+boundaryKey);
req.setHeader('Content-Length', filelen);
// the header for the one and only part (need to use CRLF here)
req.write('--' + boundaryKey + '\r\n'
// "name" is the name of the form field
// "filename" is the name of the original file
+ 'Content-Disposition: form-data; name="gamefile"; filename="image.jpg"\r\n'
// use your file's mime type here, if known
+ 'Content-Type: image/jpeg\r\n'
+ 'Content-Transfer-Encoding: binary_file_data\r\n\r\n'
);
var fileStream = fs.createReadStream('/image.jpg');
fileStream.pipe(req, { end: false }); // maybe write directly to the socket here?
fileStream.on('end', function() {
console.log("File Streamed");
// mark the end of the one and only part
req.end('--' + boundaryKey + '--\r\n\r\n');
});
在我的 php 服务器上,我在 files 数组中得到了什么:
Array
(
[gamefile] => Array
(
[name] => image.jpg
[type] =>
[tmp_name] =>
[error] => 3
[size] => 0
)
)
这意味着我的文件没有到达服务器。请建议我是否做错了什么或确实需要做其他事情。