AntdV 单个图片上传 自定义上传
文件架构1、放在components下image-uploader2、main.js 引入前端部分:1)index.vue<template><div class="clearfix"><a-uploadname="file"list-type="picture-card":file-list="fileList"@preview="handlePreview"@ch
·
文件架构
1、放在components下image-uploader
2、main.js 引入
前端部分:
1)index.vue
<template>
<div class="clearfix">
<a-upload
name="file"
list-type="picture-card"
:file-list="fileList"
@preview="handlePreview"
@change="handleChange"
:before-upload="beforeUpload"
:customRequest="uploadImage"
>
<div v-if="fileList.length === 0">
<a-icon type="plus" />
<div class="ant-upload-text" >
Upload
</div>
</div>
</a-upload>
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
<img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</div>
</template>
<script>
import { uploadImage } from '../../api/image'
export default {
data () {
return {
previewVisible: false,
previewImage: '',
imageUrl: '',
fileList: []
}
},
methods: {
handleCancel () {
this.previewVisible = false
},
async handlePreview (file) {
this.previewImage = file.url
this.previewVisible = true
},
handleChange ({ fileList }) {
this.fileList = fileList
if (this.fileList.length === 0) {
this.$emit('success', '')
}
},
beforeUpload (file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
if (!isJpgOrPng) {
this.$message.error('只能上传png、jpg、jpeg格式的图片!')
}
const isLt2M = file.size / 1024 / 1024 < 10
if (!isLt2M) {
this.$message.error('图片尺寸不能超过 10MB!')
}
return isJpgOrPng && isLt2M
},
uploadImage (file) {
const formData = new FormData()
formData.append('file', file.file)
uploadImage(formData).then(res => {
if (res.code === 0) {
this.imageUrl = process.env.VUE_APP_IMAGE_URL + res.data
this.$emit('success', res.data)
this.fileList = [{
uid: '-1',
name: 'image.png',
status: 'done',
url: this.imageUrl
}]
}
}).catch(() => {
})
}
}
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
- 引入的的 uploadImage
这里是已经封装好的 request,如果嫌麻烦,可以直接写个ajax请求,将资源发送给后台。
3、组件调用
后台部分:
效果:
更多推荐
已为社区贡献1条内容
所有评论(0)