vue图片上传总结
vue图片上传功能的实现,主要是结合element-ui中的<el-upload>组件实现
vue单图片上传:通过设置:limit="1"实现
废话不多说直接上代码:
element-ui上传页面代码如下
<div>
<el-row>
<el-col :span="2.5">
<el-upload
ref="upload"
:auto-upload="true"
:limit="1"
action="dev-api/xxx"
:on-success="handleSuccess"
:on-remove="handleRemove"
:file-list="fileList"
list-type="picture-card"
:before-upload="beforeUpload"
accept="jpg,png"
>
<i class="el-icon-plus" />
</el-upload>
</el-col>
<el-col>
<div class="el-upload__tip tip">支持JPG、PNG等图片格式</div>
</el-col>
</el-row>
</div>
js部分代码如下
// 上传图片成功后的赋值信息
handleSuccess(res) {
const preUrl = uploadPrefix + res.data.filePath
// 照片墙展示的图片信息
this.fileList.push({ url: preUrl });
// 传递后台的数据绑定信息
this.addEditResourceForm.regionBackContent = preUrl
},
// 图片上传到服务器前的格式校验
beforeUpload(file) {
const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
const extension = testmsg === 'jpg'
const extension2 = testmsg === 'png'
if (!extension && !extension2) {
this.$message({
message: '上传背景只能是jpg,png格式的图片',
type: 'warning'
})
}
return extension || extension2
},
// 删除图片
handleRemove(file, fileList) {
console.log(file, fileList)
this.addEditResourceForm.regionBackContent = null;
}
多图片上传
element-ui部分代码
<div>
<el-row>
<el-col :span="2.5">
<el-upload
ref="pcUpload"
:auto-upload="true"
action="dev-api/xxx"
:file-list="fileList"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:on-remove="handleRemove"
list-type="picture-card"
>
<i class="el-icon-plus" />
</el-upload>
</el-col>
<el-col>
<div class="el-upload__tip tip">支持JPG、PNG等图片格式</div>
</el-col>
</el-row>
</div>
js部分代码
// 上传图片成功后的赋值信息
handleSuccess(res) {
const preUrl = uploadPrefix + res.data.filePath
this.fileListArray.push(preUrl)
this.fileList.push({ url: preUrl })
this.addArticleForm.pcCarousel = this.fileListArray.join()
},
// 图片上传到服务器前的格式校验
beforeUpload(file) {
const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
const extension = testmsg === 'jpg'
const extension2 = testmsg === 'png'
if (!extension && !extension2) {
this.$message({
message: '上传背景只能是jpg,png格式的图片',
type: 'warning'
})
}
return extension || extension2
},
// 删除图片
handleRemove(file, fileList) {
this.fileList = fileList
const fileArr = []
if (fileList !== null && fileList.length > 0 && fileList !== undefined) {
for (let i = 0; i < fileList.length; i++) {
fileArr.push(fileList[i].url)
}
this.addArticleForm.pcCarousel = fileArr.join()
} else if (fileList.length === 0) {
this.addArticleForm.pcCarousel = ''
}
}
效果图如下:

好了,以上便是我在项目中遇到的图片上传问题,希望对有相同功能需求的小伙伴有帮助。
本文详细介绍了如何使用Element-UI的<el-upload>组件在Vue项目中实现单张和多张图片的上传,包括文件限制、格式验证和成功回调操作,适合初学者参考。

8444

被折叠的 条评论
为什么被折叠?



