uniapp之上传图片(加水印)至阿里云


<view style="position: absolute;top: -999999px;">
            <view>
                <canvas :style="'width:' + windowWidth + 'px;' + 'height:' + windowHeight + 'px;'"
                    canvas-id="firstCanvas"></canvas>
            </view>
</view>
//要放到首次进入页面时请求上传参数,放入缓存的话,会因为效验时间而过期,导致上传图片失败
getUploadParam() {
    let that = this;
    util.get(api.requestUrl_tc + '接口地址').then(res => {
    // console.log("上传参数", res);
    if (res.code == 1) {
    that.ossInfo = res.data
    } else {}
    })
},
//阿里云返回上传参数
accessid: ""
callback: ""
dir: "2021-07-23"
expire: 1627021230
host: "上传地址"
policy: ""
signature: "签名"
//选择图片上传
uploadRestFiles(index) {
                let that = this;
                const {
                    order
                } = that
                //#ifdef MP-WEIXIN
                uni.chooseImage({
                    count: 5,
                    // mediaType: ['image'],
                    // sizeType: ['original', 'compressed'],
                    sourceType: ['camera', 'album'],
                    // type: 'file',
                    // maxDuration: 30,
                    success(re) {
                        console.log("图片上传", re)
                        console.log("sdfsdf", re.tempFiles);
                        that.uploadFile(re.tempFiles, 'reset');
                        console.log("resetImgList", that.resetImgList);
                    }
                })
                //#endif
                //#ifdef APP-PLUS || H5
                uni.chooseImage({
                    count: 5,
                    sizeType: ['compressed'],
                    sourceType: ['camera', 'album'],
                    success: res => {
                        console.log("H5选择图片上传", res)
                        let tempFilePaths = res.tempFilePaths;
                        that.uploadFile(res.tempFilePaths, 'reset');
                    }
                });
                //#endif
            },
//多图片上传(这里涉及到画布,上传图片至阿里(formData ))
uploadFile(data, type) {
                let that = this,
                    i = data.i ? data.i : 0, //当前上传的哪张图片
                    success = data.success ? data.success : 0, //上传成功的个数
                    fail = data.fail ? data.fail : 0; //上传失败的个数
                const {
                    uploadImg,
                    optionsIndex, //点击的目标项
                    order,
                    localVal,
                    location,
                    userInfo,
                    ossInfo
                } = that;
                ImgIndex += 1;
                let fileName;
                //救援图片上传
                //#ifdef APP-PLUS || H5
                console.log("救援图片上传(h5)", data[i]);
                fileName = data[i].substring(data[i].lastIndexOf(".") + 1, data[i].length)
                //#endif
                //#ifdef MP-WEIXIN
                console.log("救援图片上传", data[i].path);
                fileName = data[i].path.substring(data[i].path.lastIndexOf(".") + 1, data[i].path.length)
                console.log("path.lastIndexOf", data[i].path.lastIndexOf(".") + 1);
                console.log("data[i].path.length", data[i].path);
                //#endif                
                console.log("fileName", fileName);
                let keyInfo = that.ossInfo.dir + '/' + that.randomString(32) + '.' + fileName;
                console.log(keyInfo, 'keyInfo')
                let uploadUrl = that.ossInfo.host;
                console.log("请求参数(oos)", ossInfo)
                let formData = {
                    'Filename': 'upload',
                    'name': 'upload',
                    'key': keyInfo,
                    'policy': that.ossInfo.policy,
                    'OSSAccessKeyId': that.ossInfo.accessid,
                    'success_action_status': '200', //让服务端返回200,不然,默认会返回204
                    'signature': that.ossInfo.signature,
                    'method': 'POST', //请求方式
                    'type': 'vehicle'
                }
                console.log(formData)
                uni.showLoading({
                    title: "图片上传中..."
                })
                console.log("增加水印功能");
                //增加水印
                uni.getImageInfo({
                    //#ifdef MP-WEIXIN
                    src: data[i].path,
                    //#endif
                    //#ifdef APP-PLUS || H5
                    src: data[i],
                    //#endif
                    //src: re.tempFilePaths[0],测试专用
                    success: (res) => {
                        // ctx.drawImage(re.tempFilePaths[0], 0,  res.width / 2, res.height /2
                        //     2)
                        //初始化画布
                        // ctx.fillRect(0, 0, res.width, res.height);
                        console.log("windowWidth", that.windowWidth, "windowHeight",
                            that
                            .windowHeight);
                        console.log("res.width", res.width, "res.height", res.height);
                        // ctx.fillRect(0, 0, that.windowWidth, that.windowHeight);
                        //324,246
                        var width = res.width
                        var height = res.height
                        //获取屏幕宽度
                        let screenWidth = uni.getSystemInfoSync().windowWidth
                        //处理一下图片的宽高的比例
                        if (width >= height) {
                            if (width > screenWidth) {
                                width = screenWidth
                            }
                            height = height / res.width * width
                        } else {
                            if (width > screenWidth) {
                                width = screenWidth
                            }
                            if (height > 400) {
                                height = 400
                                width = res.width / res.height * height
                            } else {
                                height = height / res.width * width
                            }
                        }
                        that.windowWidth = width * 2;
                        that.windowHeight = height * 2;
                        setTimeout(() => {
                            let ctx = uni.createCanvasContext('firstCanvas', this); /** 创建画布 */
                            ctx.drawImage(res.path, 0, 0, width * 2, height * 2);
                            ctx.setFillStyle('#B33836') //字体颜色
                            ctx.setFontSize(13) //字体大小
                            ctx.fillText(userInfo.company_name + "  " + userInfo.nick + "  " + userInfo
                                .mobile, 5, 20) //字体内容和位置    
                            ctx.setFillStyle('#B33836') //字体颜色
                            ctx.setFontSize(13) //字体大小                            
                            ctx.fillText("lat:" + location.lat + "  lng:" + location.lng, 5,
                                40) //字体内容和位置                            
                            ctx.setFillStyle('#B33836') //字体颜色
                            ctx.setFontSize(13) //字体大小                                
                            ctx.fillText("地址:" + localVal, 5, 60) //字体内容和位置
                            ctx.setFillStyle('#B33836') //字体颜色
                            ctx.setFontSize(13) //字体大小
                            ctx.fillText("时间:" + dateformat.dateFormatNormal(''), 5, 80) //字体内容和位置
                            ctx.draw(false, () => {
                                uni.canvasToTempFilePath({
                                    canvasId: 'firstCanvas',
                                    success: (res) => {
                                        console.log("代码996行", res);
                                        that.src = res.tempFilePath;
                                        // console.log("请求地址1111",uploadUrl);
                                        uni.uploadFile({
                                            // url: api.requestUrl_tc +'请求地址',
                                            //#ifdef MP-WEIXIN
                                            url: uploadUrl,
                                            //#endif
                                            //#ifdef APP-PLUS || H5
                                            url: '/api',(H5端使用了代理(跨域访问))
                                            //#endif                                            
                                            filePath: res.tempFilePath,
                                            name: 'file',
                                            //#ifdef MP-WEIXIN
                                            header: {
                                                'Content-Type': 'multipart/form-data',
                                                'Authori-zation': 'Bearer ' +
                                                    uni.getStorageSync(
                                                        "token_tc"),
                                            },
                                            //#endif
                                            //#ifdef APP-PLUS || H5
                                            header: {
                                                'Authori-zation': 'Bearer ' +
                                                    uni.getStorageSync(
                                                        "token_tc"),
                                            },
                                            //#endif                                        
                                            method: 'POST', //请求方式
                                            formData: formData,
                                            success: function(res) {
                                                console.log(
                                                    "阿里云返回图片信息",
                                                    res) //接口返回网络路径
                                                //var dataCode = JSON.parse(res.data)
                                                if (res.statusCode ==
                                                    200) {
                                                    success++;
                                                    console.log(
                                                        "救援图片上传成功返回((图片)服务器地址)",
                                                        res);
                                                    //如果是非其他图片上传
                                                    if (type !=
                                                        'reset') {
                                                        uploadImg.map((
                                                            item,
                                                            index
                                                            ) => {
                                                            if (item
                                                                .id ==
                                                                optionsIndex
                                                                )
                                                                item
                                                                .imgList
                                                                .push(
                                                                    uploadUrl +
                                                                    '/' +
                                                                    keyInfo
                                                                    );
                                                        })
                                                    } else {
                                                        //赋值其他图片
                                                        let obj = {}
                                                        obj.pic_id = ''
                                                        obj.url =
                                                            uploadUrl +
                                                            '/' +
                                                            keyInfo
                                                        that.resetImgList
                                                            .push(obj);
                                                        console.log(
                                                            "赋值于其他图片(画布生成之后上传服务器)",
                                                            that
                                                            .resetImgList
                                                            );
                                                    }
                                                    //目前单张上传
                                                    that.jyImaUpload(
                                                        uploadUrl +
                                                        '/' +
                                                        keyInfo,
                                                        type,
                                                        optionsIndex
                                                    )
                                                    console.log(
                                                        "optionsIndex(dddddddddd)",
                                                        optionsIndex
                                                    );
                                                } else {
                                                    uni.hideLoading()
                                                    uni.showToast({
                                                        title: res
                                                            .msg,
                                                        icon: 'none',
                                                        duration: 1300,
                                                        mask: true
                                                    })
                                                }
                                            },
                                            complete(re) {
                                                console.log("上传情况", re);
                                                console.log(i);
                                                i++; //这个图片执行完上传后,开始上传下一张
                                                console.log(i + "==" + data
                                                    .length);
                                                if (i == data
                                                    .length) { //当图片传完时,停止调用          
                                                    console.log('执行完毕');
                                                    console.log('成功:' +
                                                        success +
                                                        " 失败:" + fail);
                                                } else { //若图片还没有传完,则继续调用函数
                                                    console.log("若图片还没有传完",
                                                        i);
                                                    data.i = i;
                                                    data.success = success;
                                                    data.fail = fail;
                                                    that.uploadFile(data,
                                                        type);
                                                }
                                            },
                                            fail(res) {
                                                uni.hideLoading()
                                                fail++; //图片上传失败,图片上传失败的变量+1
                                                console.log('fail:' + i +
                                                    "fail:" +
                                                    fail);
                                            }
                                        })
                                    },
                                    complete(com) {}
                                })
                            })
                        }, 350)
                    }
   })

},
     


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM