uniapp实现图片上传功能

原创
10/18 22:04
阅读数 138
<view class="cu-bar bg-white margin-top">
    <view class="action">
        图片上传
    </view>
    <view class="action">
        {{imgList.length}}/4
    </view>
</view>
<view class="cu-form-group">
    <view class="grid col-4 grid-square flex-sub">
        <view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage"
              :data-url="imgList[index].url">
            <image :src="imgList[index].url" mode="aspectFill"></image>
            <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                <text class='cuIcon-close'></text>
            </view>
        </view>
        <view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
            <text class='cuIcon-cameraadd'></text>
        </view>
    </view>
</view>

 

<script>
    export default {
        data() {
            return {
                imgList: [],
                attachmentId: '',
            }
        },
        methods: {
            //上传图片
            ChooseImage() {
                let self = this;
                uni.chooseImage({
                    count: 4, //可选择数量,默认9
                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
                    sourceType: ['album', 'camera'], //从相册选择或从使用相机
                    success: async (res) => {
                        //上传图片大小限制
                        for (let i = 0; i < res.tempFilePaths.length; i++) {
                            if (res.tempFiles[0].size > 10 * 1024 * 1000) {  //上传图片大小限制
                                uni.showToast({
                                    title: "照片大小不能超过10MB",
                                    icon: "none"
                                });
                                return
                            }
                        }
                        try {
                            uni.showLoading({
                                title: "上传中...",
                                mask: true
                            });
                            for (let i = 0; i < res.tempFilePaths.length; i++) {
                                uni.uploadFile({
                                    url: self.$serverPath.UF + 'file/upload/' + self.attachmentId + '/app/style', //post请求的地址
                                    filePath: res.tempFilePaths[i],
                                    name: 'file',
                                    formData: {
                                        // 'username': this.userInfo.username  //formData是指除了图片以外,额外加的字段
                                    },
                                    success: (uploadFileRes) => {
                                        //这里要注意,uploadFileRes.data是个String类型,要转对象的话需要JSON.parse一下
                                        let obj = JSON.parse(uploadFileRes.data);
                                        self.attachmentId = obj.data.relationId;
                                        let image = {
                                            'id': obj.data.id,
                                            'relationId': obj.data.relationId,
                                            'url': res.tempFilePaths[i],
                                        };
                                        self.imgList.push(image);

                                    },
                                    fail: (res) => {
                                        console.log(res);
                                    }
                                })
                            }
                        } catch (e) {
                            console.log(e);
                        } finally {
                            uni.hideLoading();
                        }
                    }
                });
            },
            //查看图片
            ViewImage(e) {
                let urls = [];
                for (let i = 0; i < this.imgList.length; i++) {
                    urls.push(this.imgList[i].url);
                }
                uni.previewImage({
                    urls: urls,
                    current: e.currentTarget.dataset.url
                });
            },
            //删除图片
            DelImg(e) {
                let self = this;
                uni.showModal({
                    title: '',
                    content: '确定要删除么',
                    cancelText: '取消',
                    confirmText: '确定',
                    success: res => {
                        if (res.confirm) {
                            let index = e.currentTarget.dataset.index;
                            if (self.imgList.length != 0) {
                                let id = self.imgList[index].id;
                                let url = self.$serverPath.UF + 'file/delete/' + id;
                                this.$util.urlRequest(url, {}, 'POST', function (ret) {
                                    let res = ret.data;
                                    if (res.code == 0) {
                                        self.imgList.splice(index, 1);
                                    } else {
                                        uni.showToast({
                                            title: "删除失败,请重试",
                                            icon: "none"
                                        });
                                        console.log('请求失败:', res)
                                    }
                                });
                            }

                        }
                    }
                })
            },


        },
    }
</script>

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部