こんにちは、wattak777です。
一つだけファイルを送信する、というサンプルは幾つかあるのですが、複数ファイルの場合のサンプルをちょっと作ってみました。
サーバー側はmulterを使った以下のサンプル。
server.js
var express = require( 'express' ) ;
var app = express() ;
var multer = require( 'multer' ) ;
app.post('/file_upload', multer({dest: ファイルを置くパス}).single('my_file'), function (req, res) {
console.log(req.file.path, req.file.originalname) ;
res.sendStatus(200) ;
});
var server = app.listen(12345, function() {
console.log("listening at port %s", server.address().port) ;
});
で、本題のクライアント側は以下の実装。
request-promiseを使って同期的に送るようにしました。
client.js
const fs = require('fs') ;
const request = require('request-promise') ;
const FileNameList = [
'test1.bin',
'test2.bin',
'test3.bin'
] ;
var FileNameIndex = 0 ;
var returnCode = httpPost() ;
function httpPost() {
const FormData = {
my_file: {
value: fs.createReadStream(ファイルのパス + FileNameList[FileNameIndex]),
options: {
filename: FileNameList[FileNameIndex],
contentType: 'application/octet-stream'
}
}
}
const options = {
uri: "http://サーバーのIPアドレス:12345/file_upload",
formData: FormData,
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
}
}
var response = request(options)
.then( function(body) {
console.log( 'then :' + body ) ;
onEnd() ;
})
.catch( function(err) {
console.log( 'catch error :' + err ) ;
}) ;
return response.statusCode ;
}
function onEnd() {
console.log( 'Index ' + FileNameIndex + ' is finish.' ) ;
FileNameIndex = FileNameIndex + 1 ;
if ( FileNameIndex >= FileNameList.length ) {
console.log( 'End Operation.' ) ;
} else {
var res = httpPost() ;
}
}
console.log( 'Start Operation.' ) ;
とやると、クライアント側の表示は以下のようになります。
$ node client.js
Start Operation.
then :OK
Index 0 is finish.
then :OK
Index 1 is finish.
then :OK
Index 2 is finish.
End Operation.