vue3使用el-upload
时间: 2023-11-24 13:53:19 浏览: 192
以下是使用Vue3和Element-UI的el-upload组件实现文件上传的示例代码:
1. 首先需要在Vue组件中引入el-upload组件和axios库:
```javascript
<template>
<el-upload
class="upload-demo"
action="/upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="fileList"
:auto-upload="false"
:list-type="'picture-card'"
:multiple="true"
:limit="3"
:on-exceed="handleExceed"
:show-file-list="false">
<i class="el-icon-plus"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
import { ElUpload } from 'element-plus';
import axios from 'axios';
export default {
components: {
ElUpload,
},
data() {
return {
fileList: [],
};
},
methods: {
handlePreview(file) {
console.log('预览文件', file);
},
handleRemove(file) {
console.log('删除文件', file);
},
beforeUpload(file) {
console.log('上传前处理', file);
},
handleSuccess(response, file, fileList) {
console.log('上传成功', response, file, fileList);
},
handleError(error, file, fileList) {
console.log('上传失败', error, file, fileList);
},
handleExceed(files, fileList) {
console.log('超出文件个数限制', files, fileList);
},
},
};
</script>
```
2. 在Vue组件中实现上传文件的逻辑:
```javascript
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
const formData = new FormData();
formData.append('file', file);
axios.post('/api/upload', formData).then((response) => {
this.fileList.push({
name: file.name,
url: response.data.url,
});
}).catch((error) => {
console.log(error);
});
return false;
},
```
3. 在后端服务器中实现文件上传的逻辑:
```javascript
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
const ext = path.extname(file.originalname);
cb(null, `${Date.now()}${ext}`);
},
});
const upload = multer({ storage });
app.post('/api/upload', upload.single('file'), (req, res) => {
const file = req.file;
const url = `http://localhost:3000/${file.path}`;
res.json({ url });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
阅读全文