Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9138

Node.jsで複数ファイルを送るには

$
0
0

こんにちは、wattak777です。

一つだけファイルを送信する、というサンプルは幾つかあるのですが、複数ファイルの場合のサンプルをちょっと作ってみました。

サーバー側はmulterを使った以下のサンプル。

server.js
varexpress=require('express');varapp=express();varmulter=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);});varserver=app.listen(12345,function(){console.log("listening at port %s",server.address().port);});

で、本題のクライアント側は以下の実装。
request-promiseを使って同期的に送るようにしました。

client.js
constfs=require('fs');constrequest=require('request-promise');constFileNameList=['test1.bin','test2.bin','test3.bin'];varFileNameIndex=0;varreturnCode=httpPost();functionhttpPost(){constFormData={my_file:{value:fs.createReadStream(ファイルのパス+FileNameList[FileNameIndex]),options:{filename:FileNameList[FileNameIndex],contentType:'application/octet-stream'}}}constoptions={uri:"http://サーバーのIPアドレス:12345/file_upload",formData:FormData,method:'post',headers:{'Content-Type':'multipart/form-data'}}varresponse=request(options).then(function(body){console.log('then :'+body);onEnd();}).catch(function(err){console.log('catch error :'+err);});returnresponse.statusCode;}functiononEnd(){console.log('Index '+FileNameIndex+' is finish.');FileNameIndex=FileNameIndex+1;if(FileNameIndex>=FileNameList.length){console.log('End Operation.');}else{varres=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.

Viewing all articles
Browse latest Browse all 9138

Trending Articles