uniapp 上传方法

 封装js


const uploadUrl = ‘自己的地址’

function getImageInfo(src) {
    uni.getImageInfo({
        src,
        success(res) {
            let canvasWidth = res.width //图片原始长宽
            let canvasHeight = res.height
            let img = new Image()
            img.src = res.path
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d')
            canvas.width = 1080
            canvas.height = 1080 * (canvasHeight / canvasWidth)
            ctx.drawImage(img, 0, 0, 1080, 1080 * (canvasHeight / canvasWidth))
            canvas.toBlob(fileSrc => {
                let imgSrc = window.URL.createObjectURL(fileSrc)
                uploadFile(imgSrc)
            })
        }
    })
}
// 上传图片
function uploadFile(filePath, callback, formData) {
    uni.uploadFile({
        formData,
        url: uploadUrl,
        name: 'file',
        header: {
            // 'token': uni.getStorageSync("ACCESS_TOKEN")
        },
        filePath,
        success: (res) => {
            // let val = JSON.parse(res.data)
            // let val = JSON.parse(res.data).data.file
            // console.log(val)
            uni.hideLoading()
            callback({
                img_url: res,
                // relative_url: val.data.url
            })
        },
        fail: (err) => {
            console.log(err)
            uni.showToast({
                title: err.errMsg,
                icon: 'none'
            })
        }
    });
}


// 非h5端图片压缩
function compressImage(src, callback) {
    uni.compressImage({
        src: src,
        compressedWidth: 1000,
        success: res => {
            console.log(res);
            uploadFile(res.tempFilePath, r => {
                console.log(r, 'sssssssssssssssssss')
                callback(r)
            })
        }
    })
}

export default {
    // 图片上传
    chooseImg(params) {
        console.log(params)
        // uploadType(1 照相机,2 相册), countLimit:单次上传数量限制
        let sourceType = ['camera', 'album']
        let countLimit = params && params.countLimit || 9
        if (params && params.uploadType) {
            if (params.uploadType == 1) {
                sourceType = ['camera']
            } else if (params.uploadType == 2) {
                sourceType = ['album']
            }
        }
        return new Promise((resolve, reject) => {
            if (countLimit == 0) {
                uni.showToast({
                    title: '已达最大图片数量',
                    mask: true
                })
                reject('上传数量超过限制')
            } else {
                uni.chooseImage({
                    count: countLimit, //默认9
                    sourceType: sourceType, //从相册选择
                    sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
                    success: (res) => {
                        let arr = []
                        let pathSum = res.tempFilePaths.length
                        let tempPaths = res.tempFilePaths
                        uni.showLoading({
                            title: '图片上传中',
                            icon: 'none',
                            mask: false
                        })
                        res.tempFiles.map((item, index) => {
                            // #ifdef H5
                            // uploadFile(tempPaths[index], val => {
                            //     arr.push(val)
                            //     if (index == res.tempFiles.length - 1) {
                            //         resolve(arr)
                            //     }
                            // }, params.formData)
                            // #endif
                            // #ifndef H5
                            // compressImage(tempPaths[index], val => {
                            //     arr.push(val)
                            //     if (index == res.tempFiles.length - 1) {
                            //         resolve(arr)
                            //     }
                            // })
                            // #endif
                            uploadFile(tempPaths[index], val => {
                                arr.push(val)
                                if (index == res.tempFiles.length - 1) {
                                    resolve(arr)
                                }
                            }, params.formData)
                        })
                    },
                    // success: (res) => {
                    //     let arr = []
                    //     let pathSum = res.tempFilePaths.length
                    //     res.tempFiles.map((item, index) => {
                    //         if (item.size > 512000) {
                    //             uni.showToast({
                    //                 title: '请上传500KB以下的图片,当前图片过大',
                    //                 icon: "none"
                    //             })
                    //             if (arr.length > 0) {
                    //                 resolve(arr)
                    //             }
                    //             return
                    //         } else {
                    //             pathToBase64(item.path)
                    //                 .then(base64 => {
                    //                     $apis.upload_base_imgs({
                    //                         head_img: base64
                    //                     }).then(res1 => {
                    //                         arr.push({
                    //                             img_url: res1.img_url,
                    //                             relative_url: res1
                    //                                 .relative_url
                    //                         })
                    //                         if (index == res.tempFiles.length -
                    //                             1) {
                    //                             resolve(arr)
                    //                         }
                    //                     })
                    //                 })
                    //                 .catch(error => {
                    //                     reject('上传失败')
                    //                 })
                    //         }
                    //     })
                    // },
                    fail: (error) => {
                        reject('上传失败')
                    }
                })
            }
        })
    }
}


页面中使用
 

   	import {
		getCurrentInstance,
		ref,
		reactive,
	} from "vue"

 const $chooseImg = getCurrentInstance().appContext.config.globalProperties.$chooseImg

 const uploadAImg = () => {
        $chooseImg.chooseImg({
            formData: props.formData,
            countLimit: props.upLength - img_list.value.length
        }).then(res => {
    
        })
    } 

main.js挂载

import App from './App'
import chooseImg from "@/utils/chooseImg.js"
import store from '@/store';
import Vuex from "vuex";
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	...App
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
import uviewPlus from 'uview-plus'

// import globalComponents from './components/index'

// #ifdef H5
import "@/utils/h5.js";
// #endif

// import '@/utils/analysisProto.js'

export function createApp() {
	const app = createSSRApp(App)
	app.config.globalProperties.$chooseImg = chooseImg;
	app.use(uviewPlus)
	app.use(store)
	//全局组件
	// app.use(globalComponents)
	return {
		app
	}
}
// #endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值