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