Vue项目如何结合element-ui实现文件上传功能?下面编程教程网小编给大家简单介绍一下具体实现代码!
完整代码如下:
//前端代码
<template>
<div class="upload-form">
<el-upload :action="serverUrl" :on-success="uploadSuccess" :headers="headers"
:before-upload="beforeUpload" :on-error="uploadError">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="upload-tip">只能上传jpg/png文件,且不超过2MB</div>
</el-upload>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
serverUrl: '/api/upload',
headers: {
'Content-Type': 'multipart/form-data'
}
}
},
methods: {
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 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
uploadSuccess (response) {
console.log(response.data)
this.$message.success('头像上传成功!')
},
uploadError (error) {
console.log(error)
this.$message.error('上传头像图片失败!')
},
uploadFile (file) {
const formdata = new FormData()
formdata.append('file', file)
axios.post(this.serverUrl, formdata, {
headers: this.headers
}).then((response) => {
this.uploadSuccess(response)
}).catch((error) => {
this.uploadError(error)
})
}
}
}
</script>
<style scoped>
.upload-form {
margin-top: 20px;
text-align: center;
}
.upload-tip {
margin-top: 10px;
color: #999;
}
</style>
//后端服务器
const express = require('express')
const bodyParser = require('body-parser')
const multer = require('multer')
const app = express()
const upload = multer({ dest: 'uploads/' })
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())
app.post('/api/upload', upload.single('file'), (req, res) => {
console.log(req.file)
res.status(200).json({
success: true,
message: 'File uploaded successfully!'
})
})
app.listen(3000, () => {
console.log('Server listening on port 3000')
})
以上是编程学习网小编为您介绍的“Vue项目如何实现文件上传(附完整代码)”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。
织梦狗教程
本文标题为:Vue项目如何实现文件上传(附完整代码)


基础教程推荐
猜你喜欢
- 如何创建一个JavaScript弹出DIV窗口层的效果 2024-02-07
- 基于h5的history改善ajax列表请求体验 2022-10-17
- jquery图片放大镜效果 2023-12-27
- Vue中Element-UI日历无法缩小的问题 2023-10-08
- 微信小程序使用uni-app开发小程序及部分功能实现 2022-08-31
- 微信小程序实现监听页面滚动 2024-02-06
- layer.open()详细参数对照说明 2023-07-09
- 简单实现js页面切换功能 2024-03-09
- HTML5自定义视频播放器源码 2023-12-18
- vue 请求拦截request将token添加到请求头headers 2023-10-08