文件上传
插件:formidable
,地址:https://www.npmjs.com/package/formidable,参考里面with Express.js
部分。
html部分截图参考:
用express-generator
生成的示例代码:
const formidable = require('formidable');
var express = require('express');
var router = express.Router();/* GET home page. */
router.get('/', function (req, res, next) {res.render('index', { title: 'Express' });
});router.get('/portrait', (req, res, next) => {res.render('portrait');
});router.post('/portrait', (req, res) => {// 文件上传请求的路由规则中const form = new formidable.IncomingForm();console.log('form=====', form);// form 创建表单对象form.parse(req, (err, fields, files) => {if (err) {next(err);return;}console.log('fields',fields);console.log('files',files);// res.json({ fields, files });res.send('ok');});
})module.exports = router;
在文件上传中,可以打印fields
和files
。
fields
{ username: [ '111' ] }
files
{"files": {"portrait": [{"_events": {},"_eventsCount": 1,"_maxListeners": undefined,"lastModifiedDate": "2024-11-01T08:29:29.712Z","filepath": "C:\\Users\\xxxxx\\AppData\\Local\\Temp\\c1748ae363aa99bed12cb3700","newFilename": "c1748ae363aa99bed12cb3700","originalFilename": "微信图片_20220908091829.png","mimetype": "image/png","hashAlgorithm": false,"size": 453353,"_writeStream": "[WriteStream]","hash": null,"[Symbol(kCapture)]": false}]}
}
保存到网站根目录,一般都是public
目录下:
router.post('/portrait', (req, res) => {// 文件上传请求的路由规则中const form = new formidable.IncomingForm({multiples: true,// 设置文件上传目录uploadDir: __dirname + '/../public/images',// 保持文件后缀keepExtensions: true});console.log('form=====', form);// form 创建表单对象form.parse(req, (err, fields, files) => {if (err) {next(err);return;}console.log('fields', fields);console.log('files', files);// res.json({ fields, files });res.send('ok');});
})
服务端存储图片
form.parse(req, (err, fields, files) => {if (err) {next(err);return;}// 服务器保存该图片的访问urllet url = '/images/' + files.portrait[0].newFilename; // 后续将保存到数据库中res.send(url);});