两种方案: 这两种方案传参还是有区别额
在nodeJs中上传附件调用了 multer 的中间件,采用这个中间件来上传
首先是表单(前端部分):
<!DOCTYPE html> <html> <head> <title>nodejs文件上传</title> <script src="/javascripts/jquery.min.js"></script> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input name="fileUpload" type="file" /> <!--1--> <img src="" > <button type="submit">上传</button> </form> <script> (function($){ $(‘input‘).on(‘change‘, function(event) { var files = event.target.files, reader = new FileReader(); if(files && files[0]){ reader.onload = function (ev) { $(‘img‘).attr(‘src‘, ev.target.result); } reader.readAsDataURL(files[0]); } }) }(jQuery)) </script> </body> </html>
服务器端:
var express = require(‘express‘); var router = express.Router(); var multer = require(‘multer‘); var fs = require(‘fs‘); const UPLOAD_PATH = ‘./uploads‘ var upload = multer({ dest: UPLOAD_PATH }) /* GET home page. */ router.get(‘/‘, function(req, res, next) { res.render(‘index‘, { title: ‘Express‘ }); }); //多文件上传 // router.post(‘/upload‘, upload.array(‘fileUpload‘), function (req, res, next) { // const files = req.files; // const response = []; // const result = new Promise((resolve, reject) => { // files.map((v) => { // fs.readFile(v.path, function(err, data) { // fs.writeFile(`${UPLOAD_PATH}/${v.originalname}`, data, function(err, data) { // const result = { // file: v, // } // if (err) reject(err); // resolve(‘成功‘); // }) // }) // }) // }) // result.then(r => { // res.json({ // msg: ‘上传成功‘, // }) // }).catch(err => { // res.json({ err }) // }); // }) //单个文件上传 router.post(‘/upload‘, upload.single(‘fileUpload‘), function (req, res, next) { const { file } = req; console.log(req.files); fs.readFile(file.path, function(err, data) { fs.writeFile(`${UPLOAD_PATH}/${file.originalname}`, data, function (err) { if (err) res.json({ err }) res.json({ msg: ‘上传成功‘ }); }); }) }) module.exports = router;
这事表单上传还有一种就是用异步上传(我比较常用的一种)
这种的话需要怼传输的数据进行重新封装 (首先把所得的数据封装为FormData 然后给后台)
let _this = this; document.getElementById(‘upload‘).onchange = function (e) { let file = e.target.files[0]; var formData = new FormData(); formData.append(‘fileUpload‘, file); _this.axios.post(‘/user/file-upload‘, formData).then(function (response) { if (response.data.state === 200) { _this.imageUrl = _this.$store.state.imgBaseUrl + response.data.result; _this.registerFromData.imageUrl = response.data.result; } }); }