uniapp小程序选择文件并上传到uniCloud

uniapp小程序选择文件并上传到uniCloud

官方文档:https://uniapp.dcloud.io/api/README

主要使用了chooseMessageFile(暂时支持选择聊天记录文件),saveTmpfile,uploadfile这三个API

1、选择文件

chooseFile:function(){
    
    
    let that = this;
    uni.chooseMessageFile({
    
    
        count: 1,
        success: res => {
    
    
            //filename是自动获取到的文件名称
            let filename = res.tempFiles[0].name,
            //获取到的文件路径
                filePath = res.tempFiles[0].path,
                houzhuiming = that.getHouzhui(filePath,'.');//获取上传文件后缀名
            //保存filename
            that.filename = filename;
            //通过后缀名判断文件类型
            if(['jpg','png','jpeg'].indexOf(houzhuiming) != -1){
    
    
                //如果是图片直接将filepath赋值给img绑定为图片的src,可以在页面上展示·
                that.img = filePath;
                //预览图片
                uni.previewImage({
    
    
                    //对选中的图片进行预览
                    urls: filePath,
                })
            }else{
    
    
                //不是图片的话,将准备好的图片展示出来
                that.img = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-b06b1ef6-bb41-4224-9b73-8d3e34b7ed2f/a3ab7bba-3522-4244-98fa-d9f770407582.png';
            }
            //保存临时文件,需要保存为临时文件,后面才可以上传到unicloud,不然图片的临时路径会失效
            that.saveTmpfile(filePath);
        }
    })
}

2、保存临时文件

//保存临时文件
saveTmpfile: function(filepath){
    
    
    let that = this;
    uni.saveFile({
    
    
    tempFilePath: filepath,
    success: function (res) {
    
    
        //保存后的文件路径
        var savedFilePath = res.savedFilePath;
        that.savedFilePath = savedFilePath;
        }
    });
},

3、上传文件到unicloud

//上传文件到云存储空间
uploadfile: function(filePath,name){
    
    
    //显示加载弹窗
    uni.showLoading({
    
    
        mask:true,
        title:'正在上传文件,请稍等……'
    })
    // promise方式
    const result = uniCloud.uploadFile({
    
    
        filePath: filePath,
        cloudPath: name,
        onUploadProgress: function(progressEvent) {
    
    
            console.log(progressEvent);
            var percentCompleted = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
            );
        }
    }).then(res => {
    
    
        uni.hideLoading();
        uni.showToast({
    
    
            title:"上传成功",
            duration:1000
        })
    });
},

猜你喜欢

转载自blog.csdn.net/Twinkle_sone/article/details/115356695