最近在學(xué)習(xí)node實(shí)現(xiàn)一個(gè)后臺(tái)管理系統(tǒng),用到了圖片上傳,有一些小問題記錄一下~
直接上代碼,問題都記錄在注釋里~
const express = require('express');const path = require('path');const multer = require('multer');const app = new express();// 設(shè)置靜態(tài)目錄 第一個(gè)參數(shù)為虛擬的文件前綴,實(shí)際上文件系統(tǒng)中不存在// 可以用public做為前綴來加載static文件夾下的文件了app.use('/public', express.static(path.join(__dirname, './static')));// 根據(jù)當(dāng)前文件目錄指定文件夾const dir = path.resolve(__dirname, '../static/img');// 圖片大小限制KBconst SIZELIMIT = 500000;const storage = multer.diskStorage({ // 指定文件路徑 destination: function(req, file, cb) { // !!!相對路徑時(shí)以node執(zhí)行目錄為基準(zhǔn),避免權(quán)限問題,該目錄最好已存在* // cb(null, './uploads'); cb(null, dir); }, // 指定文件名 filename: function(req, file, cb) { // filedname指向參數(shù)key值 cb(null, Date.now() + '-' + file.originalname); }});const upload = multer({ storage: storage});app.post('/upload', upload.single('file'), (req, res) => { // 即將上傳圖片的key值 form-data對象{key: value} // 檢查是否有文件待上傳 if (req.file === undefined) { return res.send({ errno: -1, msg: 'no file' }); } const {size, mimetype, filename} = req.file; const types = ['jpg', 'jpeg', 'png', 'gif']; const tmpTypes = mimetype.split('/')[1]; // 檢查文件大小 if (size >= SIZELIMIT) { return res.send({ errno: -1, msg: 'file is too large' }); } // 檢查文件類型 else if (types.indexOf(tmpTypes) < 0) { return res.send({ errno: -1, msg: 'not accepted filetype' }); } // 路徑可根據(jù)設(shè)置的靜態(tài)目錄指定 const url = '/public/img/' + filename; res.json({ errno: 0, msg: 'upload success', url });});app.listen(3000, () => { console.log('service start');});附上文檔參考鏈接:
express框架
path模塊
multer
最后再附贈(zèng)一個(gè)node自動(dòng)重啟工具nodemon
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。
新聞熱點(diǎn)
疑難解答
圖片精選