在 nodeJs 服务中 读取到文件流,并且传往后台
const fs = require('fs'); const fetch = require('node-fetch'); const FormData = require('form-data'); var file = fs.createReadStream("./static/test.war"); var form = new FormData(); form.append("file",file); fetch('http://192.168.179.131:8010/file/uploadFile', { method: "POST", body: form, headers: form.getHeaders() // 这步非常重要一定要把formdata的headers放在请求体headers中我发现网上很多例子讲的都没这个headers,没有这个后台还是会报boundary的错因为boundary是在request headers中 }).then(res => res.text()).then(data =>{ console.log(data); });
nodeJs 充当中转站 转发到后台
const multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); const path = require('path'); //导入功能模块 var express = require('express'); //创建服务器对象,实例,一个应用程序 var app = express(); var bodyParser = require('body-parser'); //urlencoded() 对url进行编码 //extended:true 是否对编码格式开始高级编码 app.use(bodyParser.urlencoded({extended: true})); //express.static("www")托管静态资源,参数是静态资源的文件夹 app.use(express.static("static")); //listen(端口号,执行方法)用来监听指定端口号 app.listen(8082, function () { console.log("服务器启动成功,监听端口:%d", 8082); }); //添加一个请求方式为get的接口 //get(接口路径,执行方法(req,resp)) // 获取 头部参数 getParam = function (req, paramName) { return (req.body[paramName]) ? req.body[paramName] : req.query[paramName]; } const uploadFile = require("./fileUtil"); app.post("/fileUpload.do", multipartMiddleware, function (req, resp) { // 获取上传到node的文件 const {path: filePath, originalFilename} = req.files.file; // 得到newPath新地址用于创建读取流 const newPath = path.join(path.dirname(filePath), originalFilename); uploadFile.uploadFile(filePath,newPath,resp); });
fileUtil.js
const fs = require("fs"); const FormData = require('form-data'); const fetch = require('node-fetch'); var fileUtil = { uploadFile: (filePath,newPath,resp) => { fs.rename(filePath, newPath, (err) => { if (err) { console.log(err.message); return; } else { //创建读取流 const file = fs.createReadStream(newPath); // new formdata实例 const form = new FormData() ; // 把文件加入到formdata实例中 form.append('file', file); fetch('http://127.0.0.1:8080/file/uploadFile', { method: "POST", body: form, // 这步非常重要一定要把formdata的headers放在请求体headers中,没有这个后台还是会报boundary的错因为boundary是在request headers中 headers: form.getHeaders() }).then(res => res.json()).then(data => { console.log(data); resp.send(data); }); } }); }, } module.exports = fileUtil;