Vue项目如何结合element-ui实现文件上传功能?下面web建站小编给大家简单介绍一下具体实现代码!
完整代码如下:
//前端代码
<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')
})
一款免费开源的JavaScript文件上传组件—— Uppy
上面是“Vue项目如何实现文件上传(附完整代码)”的全面内容,想了解更多关于 vuejs 内容,请继续关注web建站教程。
当前网址:https://ipkd.cn/webs_4863.html
workflows工作流
一个骷髅海盗船长ComfyUI工作流
图生图工作流:粉红色梦幻家园comfyui工作流
瀑布边坐着一位披着斗篷的隐士
一颗翡翠玉雕盆栽树comfyui工作流
在白雪覆盖的广阔平原上两只可爱的小猫
一个外国人在吹奏萨克斯ComfyUI工作流
一个神秘的隐藏面孔下一本书的剪影ComfyUI工作流
一盒用五颜六色的食材烹制的热气腾腾的寿司
猜你喜欢
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

利用css绘画棋盘布局(象棋)
css3搭积木叠加图形
纯css翻书效果
js实现table表格动态新增行和列表
自动打字效果(惊喜在后面)
黑客入侵效果代码
css3卡片动态滑动效果
利用js做一个炫酷音乐背景效果







