nodeJS作为中间层上传文件
1.使用form-data插件 new FromData() 上传
2. 前端上传之后 文件流的格式转换了,所以node需要将数据处理为formData格式进行上传至后台
var express = require('express'); var path = require('path'); var request = require('request'); var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); var fs = require('fs'); var qs = require('querystring'); var config = require('config');
// 插件form-data const FormData = require('form-data') app.post('/erm/*', multipartMiddleware, function(req, res) { var h_auth = ''; var h_date = ''; var body = req.body; // only accept json format console.log(body) if(req.originalUrl.includes('/erm/bi')){ let default_host = HOST; req.originalUrl = req.originalUrl.substring(4, req.originalUrl.length); default_host = OTA_HOST; // 上传文件 if(default_host == OTA_HOST && req.originalUrl.includes('/bi/shipment/equipments')){
// 处理文件 const { path: filePath, originalFilename } = req.files.file // const newPath = path.join(path.dirname(filePath), originalFilename) const file = fs.createReadStream(filePath) let form = new FormData(); form.append('file', file); form.append('id', body['id']); form.append('name', body['name']); form.append('saleName', body['saleName']); form.append('userId', body['userId']); if(req.session.sign) { const sign = req.session.sign; // console.log('>token: '+sign.token); // console.log('>tokenSecret: '+sign.tokenSecret); var date = moment(new Date).format("YYYY-MM-DD HH:mm:ss"); text = hmacSHA1(sign.token, sign.tokenSecret, date, 'POST', req); req.paramHeader.headers['Authorization'] = text; req.paramHeader.headers['X-Xiaoyi-Date'] = date; h_auth = text; h_date = date; }
// 请求参数配置 var options = { url: default_host + req.originalUrl, headers: { 'Content-Type': 'multipart/form-data', 'Authorization': h_auth, 'X-Xiaoyi-Date': h_date, }, formData: { 'id': body['id'], 'name': body['name'], 'saleName': body['saleName'], 'file': file }, }; request.post(options, function(err, resp, data) { if (data) { const body = JSON.parse(data); console.log(body); const result = body.result; const code = body.code; const message = body.message; if(code == 1) { res.json(body); } else { res.json({code:code, message:message, result:result}); } } else { res.json({code:'500', message:'fail', result:'fail'}); } }); return false; } } });