node+multer實現圖片上傳的示例程式碼
阿新 • • 發佈:2020-02-19
最近在學習node實現一個後臺管理系統,用到了圖片上傳,有一些小問題記錄一下~
直接上程式碼,問題都記錄在註釋裡~
const express = require('express'); const path = require('path'); const multer = require('multer'); const app = new express(); // 設定靜態目錄 第一個引數為虛擬的檔案字首,實際上檔案系統中不存在 // 可以用public做為字首來載入static資料夾下的檔案了 app.use('/public',express.static(path.join(__dirname,'./static'))); // 根據當前檔案目錄指定資料夾 const dir = path.resolve(__dirname,'../static/img'); // 圖片大小限制KB const SIZELIMIT = 500000; const storage = multer.diskStorage({ // 指定檔案路徑 destination: function(req,file,cb) { // !!!相對路徑時以node執行目錄為基準,避免許可權問題,該目錄最好已存在* // cb(null,'./uploads'); cb(null,dir); },// 指定檔名 filename: function(req,cb) { // filedname指向引數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' }); } // 路徑可根據設定的靜態目錄指定 const url = '/public/img/' + filename; res.json({ errno: 0,msg: 'upload success',url }); }); app.listen(3000,() => { console.log('service start'); });
附上文件參考連結:
express框架
path模組
multer
最後再附贈一個node自動重啟工具nodemon
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。