多图上传,发送端:
var express = require('express') var rp = require('request-promise') var fs = require("fs"); var app = express() app.get('/send', function(req, res, next) { var options = { method: 'POST', uri: 'http://127.0.0.1:3000/profile', formData: { avatar: [fs.createReadStream("./ad.jpg"), fs.createReadStream("./222.png")] }, headers: { // 'content-type': 'application/x-www-form-urlencoded' } }; rp(options) .then(function(body) { // POST succeeded... res.send(body); }) .catch(function(err) { // POST failed... res.send(err); }); }); app.listen(3001);
接收端:
var express = require('express') var multer = require('multer') var _ = require("lodash"); var app = express() var storage = multer.diskStorage({ //设置上传后文件路径,uploads文件夹会自动创建。 destination: function(req, file, cb) { cb(null, './uploads') }, //给上传文件重命名,获取添加后缀名 filename: function(req, file, cb) { var fileFormat = (file.originalname).split("."); cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); } }); var fileFilter = function(req, file, cb) { cb(null, false); //这里设置为false则直接拒绝上传了,实际使用应为true } //添加配置文件到muler对象。 var upload = multer({ storage: storage, fileFilter: fileFilter }); var up = upload.array('avatar'); app.post('/profile', function(req, res, next) { // req.file 是 `avatar` 文件的信息 up(req, res, function(err) { if (err) { // An error occurred when uploading res.send(err); return } res.send("upload success"); // Everything went fine }) }); app.post('/profile2', function(req, res, next) { // req.file 是 `avatar` 文件的信息 console.log(req.body); res.json({ "succ": true, "msg": "请求成功" }); }); app.listen(3000);