nodejs+vue+ElementUi网盘文件管理系统的设计与实现
由于篇幅所限,以下仅展示如何使用Express.js
和Vue.js
创建一个简单的文件上传接口,以及如何在Vue
应用中使用Element UI
进行文件上传。
后端 (Express.js):
安装express
和multer
:
npm install express multer
创建一个简单的服务器,并设置multer
进行文件上传:
const express = require('express');
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/') // 确保这个文件夹已经存在
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage })
app.post('/upload', upload.single('file'), (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).send('No file uploaded.');
}
res.send('File uploaded successfully.');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
前端 (Vue.js + Element UI):
安装vue
和element-ui
:
npm install vue element-ui
在Vue
组件中使用Element UI
的Upload
组件:
<template>
<el-upload
class="upload-container"
action="http://localhost:3000/upload"
:on-success="handleSuccess"
:on-error="handleError"
:before-upload="beforeUpload">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</el-upload>
</template>
<script>
import { Upload, Button } from 'element-ui'
export default {
components: {
'el-upload': Upload,
'el-button': Button
},
methods: {
handleSuccess(response, file, fileList) {
console.log('File uploaded successfully:', response);
},
handleError(err, file, fileList) {
console.error('Error uploading file:', err);
},
beforeUpload(file) {
// 在这里可以添加文件上传前的校验逻辑
},
submitUpload() {
this.$refs.upload.submit();
}
}
}
</script>
确保你的Vue
项目中的main.js
引入了Element UI
:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
Vu
评论已关闭