1 const fs = require('fs') 2 const path = require('path') 3 const FormData = require('form-data') 4 const express = require('express') 5 const fetch = require('node-fetch') 6 const router = express.Router() 7 const multipart = require('connect-multiparty'); 8 var multipartMiddleware = multipart() 9 router.post('/uploadFile', multipartMiddleware, (req, res) => { 10 const { path: filePath, originalFilename } = req.files.file 11 const newPath = path.join(path.dirname(filePath), originalFilename) // 獲得newPath新地址用於建立讀取流 12 fs.rename(filePath, newPath, (err) => { 13 if (err) { 14 return; 15 } else { 16 const file = fs.createReadStream(newPath) //建立讀取流 17 const form = new FormData() // new formdata實例 18 form.append('file', file) // 把文件加入到formdata實例中 19 fetch('後臺接口上傳地址like:https://ip:端口/接口', { 20 method: "POST", 21 body: form, 22 headers: form.getHeaders() // 這步很是重要必定要把formdata的headers放在請求體headers中我發現網上不少例子講的都沒這個headers,沒有這個後臺仍是會報boundary的錯由於boundary是在request headers中 23 }).then(res => res.json()).then(data => { 24 res.send({data: data}) //將上傳結果返回給前端 25 }) 26 } 27 }) 28 });
1 const fs = require('fs') 2 const path = require('path') 3 const FormData = require('form-data') 4 const express = require('express') 5 var http = require('http'); 6 const router = express.Router() 7 const multipart = require('connect-multiparty'); 8 var multipartMiddleware = multipart() 9 router.post('/uploadFile', multipartMiddleware, (req, res) => { 10 const { path: filePath, originalFilename } = req.files.file 11 const newPath = path.join(path.dirname(filePath), originalFilename) // 獲得newPath新地址用於建立讀取流 12 fs.rename(filePath, newPath, (err) => { 13 if (err) { 14 return; 15 } else { 16 const file = fs.createReadStream(newPath) //建立讀取流 17 const form = new FormData() // new formdata實例 18 form.append('file', file) // 把文件加入到formdata實例中 19 var request = http.request({ 20 method: 'post', 21 host: 'http://ip:port', 22 path: '/xxxx', //上傳接口 23 headers: form.getHeaders() //formdata的headers 24 }); 25 form.pipe(request); 26 request.on('response', (response) => { 27 res.send({data: response}) 28 }); 29 } 30 }) 31 })
這種方式使用的是node中http方式,相關注意事項其實跟node-fetch差很少只是發送的差異而已。前端