上传图片的问题
这是封装的上传照片组件
<template>
<div>
<el-upload
:action="action"
:headers="requestHeader"
accept=".png, .jpg, .gif, .jpeg"
list-type="picture-card"
:file-list="fileList"
:on-success="handleSuccess"
:on-preview="handlePreview"
:on-remove="handleRemove"
:limit="limit"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<el-image v-for="(url, key) in handleData" :key="key" :src="url" :preview-src-list="handleData" class="view_img"> </el-image>
</el-dialog>
</div>
</template>
<script>
import { getToken } from '@/utils/auth'
export default {
name: 'UploadImg',
props: {
handleData: {
type: Array,
default: () => [],
},
limit: {
type: Number,
default: 999,
},
callbackHandle: {
type: Function,
default: () => () => {},
},
},
data() {
return {
action: process.env.VUE_APP_BASE_API + '/common/uploadFile',
requestHeader: { Authorization: getToken() },
dialogVisible: false,
}
},
computed: {
fileList() {
if (this.handleData) {
return this.handleData.map((url, key) => {
return { name: `图片${key + 1}`, url }
})
}
return []
},
},
methods: {
handleRemove(file, fileList) {
console.log('handleRemove', fileList)
const imgList = fileList.map(item => item.url)
this.callbackHandle(imgList)
},
handlePreview(file) {
this.dialogVisible = true
},
// 上传成功加入数组, 成功之后回调
handleSuccess(response, file, fileList) {
const imgList = fileList.map((item) => {
if (item.response) {
if (item.response.code === 200) {
if (item.response.data.code === 200) {
return item.response.data.data.oss_url
} else {
this.$message.error('图片上传接口报错!')
return
}
} else {
this.$message.error('图片上传失败!')
return
}
} else {
return item.url
}
})
this.callbackHandle(imgList)
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`)
},
},
}
</script>
<style lang="scss" scoped>
.view_img {
width: 100px;
height: 100px;
}
</style>
上传的组件
<el-form-item label="上传附件:" prop="name">
<el-upload
ref="upload"
:action="action"
:headers="requestHeader"
accept=".png, .jpg, .gif, .jpeg"
list-type="picture-card"
:file-list="fileList"
:on-success="handleSuccess"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</el-form-item>
return {
action: process.env.VUE_APP_BASE_API + '/common/uploadFile',
}
method里面的操作
// 图片 - 上传成功
handleSuccess(response, file, fileList) {
const imgList = fileList.map((item) => {
if (item.response.code === 200) {
return item.response.data.data.oss_url
}
return ''
})
this.form.prod_img = imgList.join(',')
},
// 图片 - 删除
handleRemove(file, fileList) {
const imgList = fileList.map((item) => {
if (item.response.code === 200) {
return item.response.data.data.oss_url
}
return ''
})
this.form.prod_img = imgList.join(',')
},
// 图片 - 浏览
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},