<w-compress ref='wCompress' />
<u-upload accept="image" id="upload" width="150" height="150" style="margin-left: 40rpx;"
:previewFullImage="true" :headers="headers" :fileList="fileList1" @afterRead="afterRead"
@delete="deletePic" name="1" multiple :maxCount="6">
</u-upload>
import {deleteImg} from '@/api/xxx.js';
data() {
      return {
        fileList1:[],//存放图片的列表
        ImageId: [], //存放所有图片的id
      }          
}
methods:{
    // 删除图片
    deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
        let idArr = []; //存储删除图片的id值,保存到数组中
        deleteImg(Array(this.ImageId[event.index])).then(res => {
            console.log(res);
            this.ImageId.splice(event.index, 1);
            console.log(this.ImageId)
        }).catch(res => {
            console.log(res);
        })
    },

    //压缩图片
    async compress(files) { //图片压缩并上传
    console.log(files)
        const that = this
        let compressFile = []
        //循环压缩并上传
        await that.$refs.wCompress.start(files, { //调用压缩组件方法
                // pixels: 630000,  // 最大分辨率,默认二百万
                quality: 0.8, // 压缩质量,默认0.8     
                base64: false, // 是否返回base64,默认false,非H5有效
            })
            .then(res => {
                 this.uploadFilePromise(res) //调用上传方法
            })
            .catch(e => {
                console.log(e)
            })

    },


    // 新增图片
    async afterRead(event) {
        console.log(event)
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
            this[`fileList${event.name}`].push({
                ...item,
                status: 'uploading',
                message: this.$t("Shopping.productImgUploading")
            })
        })

        for (let i = 0; i < lists.length; i++) {
            await this.compress(lists[i].url);
            let item = this[`fileList${event.name}`][fileListLen]
            this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                status: 'success',
                message: '',
            }))
            fileListLen++
        }
    },
    //每新增一张图片,向后台获取一个id值
     async uploadFilePromise(url) {
         await new Promise((resolve, reject) => {
            let a = uni.uploadFile({
                url: config.baseUrl + '/system/oss/upload', // 仅为示例,非真实的接口地址
                filePath: url,
                name: 'file',
                header: {
                    "Authorization": "Bearer " + getToken()
                },
                success: (res) => {
                    var data =  JSON.parse(res.data);
                    this.ImageId.push(data.data.ossId);
                    resolve(res.data.data)
                }
            });
        })
    },
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐