uniapp 图片选择并上传

400 阅读1分钟
// 图片选择并上传
upload: function(num, params, callback, url) {
    var app_type ='h5';
    var app_type_name ='H5';
    
    var data = {
        token: 'token',
        app_type: app_type,
        app_type_name: app_type_name
    }
    
    data = Object.assign(data, params); // 整合外部传入的参数

    var that = this;
    // 选择图片
    uni.chooseImage({
        count: num, // 选择图片数
        sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
        sourceType: ['album', 'camera'], //从相册或者拍照
        success: async function(res) {
            const tempFilePaths = res.tempFilePaths;
            var _data = data;
            var imgs = [];
            uni.showLoading({title: '上传中'})
            for (var i = 0; i < tempFilePaths.length; i++) {
                var path = await that.uploadFile(tempFilePaths[i], _data, params.path,
                    url);
                imgs.push(path);
                if (imgs.length == tempFilePaths.length) {
                    uni.hideLoading()
                    uni.showToast({
                        title: '上传成功'
                    })
                    typeof callback == 'function' && callback(imgs);  // 上传成功回调
                }
            }
        },
        fail: err => {
            uni.hideLoading()
            uni.showToast({
                title: '上传失败'
            })
        }
    });
},
//上传图片
uploadFile(tempFilePath, data, path, url = "", callback) {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: url, // 上传接口
            filePath: tempFilePath,
            name: 'field',
            header: {
                'X-Token': data.token,
            },
            success: function(res) {
                var path_str = JSON.parse(res.data);
                if (path_str.status == 200) {
                    // 上传成功
                    resolve(path_str.data.path);
                    typeof callback == 'function' && callback(path_str.data.path);
                } else {
                    reject("error");
                }
            }
        });
    });
}

// 使用

<view @click="uploadImage">
    上传
</view>

uploadImage() {
    this.upload(1, {}, (path) => {
        console.log(path)
    });
} 

参考链接:

uniapp.dcloud.net.cn/api/media/i…

uniapp.dcloud.net.cn/api/request…

uploadImg: function(opt, successCallback, errorCallback) {
    let that = this;
    if (typeof opt === 'string') {
        let url = opt;
        opt = {};
        opt.url = url;
    }
    let count = opt.count || 1,
        sizeType = opt.sizeType || ['compressed'],
        sourceType = opt.sourceType || ['album', 'camera'],
        is_load = opt.is_load || true,
        uploadUrl = opt.url || '',
        inputName = opt.name || 'pics',
        fileType = opt.fileType || 'image';
    uni.chooseImage({
        count: count, //最多可以选择的图片总数  
        sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有  
        sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有  
        success: function(res) {
            //启动上传等待中...  
            uni.showLoading({
                title: i18n.t(`图片上传中`),
            });
            uni.uploadFile({
                url: HTTP_REQUEST_URL  + uploadUrl,
                filePath: res.tempFilePaths[0],
                fileType: fileType,
                name: inputName,
                formData: {
                    'filename': inputName
                },
                header: {
                    // #ifdef MP
                    "Content-Type": "multipart/form-data",
                    // #endif
                    [TOKENNAME]: 'Bearer ' + store.state.app.token
                },
                success: function(res) {
                    uni.hideLoading();
                    if (res.statusCode == 403) {
                        uni.showToast({
                            title: res.data
                        });
                    } else {
                        let data = res.data ? JSON.parse(res.data) : {};
                        if (data.status == 200) {
                            successCallback && successCallback(data)
                        } else {
                            errorCallback && errorCallback(data);
                            uni.showToast({
                                title: data.msg
                            });
                        }
                    }
                },
                fail: function(res) {
                    uni.hideLoading();
                    uni.showToast({
                        title: i18n.t(`上传图片失败`)
                    });
                }
            })
        }
    })
}

uploadpic() {
    this.$util.uploadImageOne({
        url:'upload/image',
        sourceType:['album']
    }, (res) => {
        console.log(res.data.url)
    });
}