node?+?multer?實(shí)現(xiàn)文件上傳過程
node + multer 實(shí)現(xiàn)文件上傳
介紹
使用Node.js中的express框架和multer,實(shí)現(xiàn)文件的上傳
實(shí)現(xiàn)
1. 前端
<el-upload
? ? ? ? class="upload-demo"
? ? ? ? action="http://localhost:5678/uploadModel"
? ? ? ? :show-file-list="false"
? ? ? ? :on-success="getUploadSuccess"
? ? ? ? >
? ? ? ? <el-button size="small" type="primary">點(diǎn)擊上傳</el-button>
</el-upload>
getUploadSuccess(res, file) {
? ? ? // this.avatar = res.avatar;
? ? ? // console.log(564);
? ? ? this.$message({
? ? ? ? type: "success",
? ? ? ? message: "模型上傳成功!",
? ? ? });
? ? },通過element ui組件庫中的el-upload上傳組件和el-button按鈕
點(diǎn)擊上傳按鈕,激活el-upload組件的action調(diào)用對應(yīng)的后端接口
2. 后端接口
var multer = require('multer');
// 此操作會創(chuàng)建uploads文件夾,也可理解為最終存儲的目標(biāo)文件夾,服務(wù)啟動就會自動創(chuàng)建
var upload = multer({ dest: 'Simulation_Model/' });
// 此操作理解為,將文件暫時(shí)儲存在這個(gè)文件夾中
var storage = multer.diskStorage({
? ? destination: function (req, file, cb) {
? ? ? ? cb(null, './Simulation_Model')
? ? },
? ? filename: function (req, file, cb) {
? ? ? ? cb(null, file.originalname)
? ? }
})
var upload = multer({ storage: storage })
// 調(diào)用接口,上傳文件
app.post('/uploadModel', upload.single('file'), function (req, res, next) {
? ? if (req.file === undefined) {
? ? ? ? return res.send("模型上傳失敗!");
? ? }
? ? // fs.renameSync(oldpath, newpath);新路徑和舊路徑都要存在
? ? // 將文件從舊文件夾剪切到新文件夾中,由于我們只需要一個(gè)文件夾,所以新路徑與舊路徑相同,
? ? fs.renameSync('./Simulation_Model/' + req.file.filename, "./Simulation_Model/" + req.file.originalname);
? ? res.send("模型上傳成功!");
})上傳成功后,文件保存在后端目錄的Simulation_Model文件夾內(nèi)
node+express+multer 實(shí)現(xiàn)單文件上傳、下載
routes/index.js
- node express 部署到服務(wù)器,用pm2進(jìn)行管理。啟動的時(shí)候需要進(jìn)去 /bin 目錄
- 服務(wù)器 上傳文件路徑 : “.. /public/uploads”
- 本地上傳文件路徑 : “./public/uploads”
- 下載文件不能通過ajax請求和axios,需要通過a標(biāo)簽或者
window.location.herf = '下載文件接口'
下載文件的接口需要寫成get請求方式
/*
* @Author: 471826078@qq.com
* @Date: 2020-05-21 09:48:04
* @LastEditors: 471826078@qq.com
* @LastEditTime: 2020-06-12 14:42:17
*/
var express = require('express');
var router = express.Router();
const multer = require('multer')
const path = require('path')
const http = require('http')
const fs = require('fs')
let upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
// cb(null, './public/uploads'); //本地
cb(null, '../public/uploads'); //服務(wù)器
},
filename: function (req, file, cb) {
var changedName = new Date().toISOString().replace(/:/g, '-') +'-'+ file.originalname;
cb(null, changedName);
}
})
})
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
//單個(gè)圖片文件上傳
router.post('/uploadImage', upload.single('file'), (req, res) => {
if (!req.file) { //判斷一下文件是否存在,也可以在前端代碼中進(jìn)行判斷。
res.json({
code: 0,
message: "上傳文件不能為空!",
data: null
})
return false
}
//返回路徑需要轉(zhuǎn)義 否則會返回反斜杠格式數(shù)據(jù) 導(dǎo)致微信小程序識別不了本地圖片 http://localhost:8888//uploads\images\1582511344098-1.jpg
let filePath = req.file.path;
let pathResult = filePath.split('\\').join('/');
res.json({
code: 1,
type: 'uploadImage',
message: "上傳成功!",
data: req.file.path,
originalname: req.file.originalname,
path:'線上服務(wù)地址' + pathResult
})
});
//下載文件
router.get('/download',(req, res, next)=>{
const name = req.body.name;
console.log(name)
var path = '../public/download/'+ name;
var size = fs.statSync(path).size;
var f = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': 'application/force-download',
'Content-Disposition': 'attachment; filename=' + name,
'Content-Length': size
});
f.pipe(res);
})
module.exports = router;
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
nodejs連接mysql數(shù)據(jù)庫及基本知識點(diǎn)詳解
這篇文章主要介紹了nodejs連接mysql數(shù)據(jù)庫,結(jié)合實(shí)例形式總結(jié)分析了nodejs連接與操作mysql數(shù)據(jù)庫的相關(guān)模板、配置及mysql數(shù)據(jù)庫查詢、添加數(shù)據(jù)等操作技巧,需要的朋友可以參考下2018-03-03
node.js實(shí)現(xiàn)websocket的即時(shí)通訊詳解
這篇文章主要介紹了深入淺出講解websocket的即時(shí)通訊,服務(wù)器可以主動向客戶端推送信息,客戶端也可以主動向服務(wù)器發(fā)送信息,是真正的雙向平等對話,屬于服務(wù)器推送技術(shù)的一種,需要的朋友可以參考下2023-05-05
用node開發(fā)并發(fā)布一個(gè)cli工具的方法步驟
這篇文章主要介紹了用node開發(fā)并發(fā)布一個(gè)cli工具的方法步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01

