uni-file-picker文件选择上传

基础用法

mode=”grid” ,可以使用九宫格样式选择图片

limit=”1″ ,则最多选择张图片

file-mediatype=”image”,限定只选择图片

file-extname=’png,jpg’,限定只选择 png和jpg后缀的图片

auto-upload=”false”,可以停止自动上传,通过ref调用upload方法自行选择上传时机。与ref=”files”搭配使用,this.$refs.files.upload()。



    export default {
        data() {
            return {
                imageValue:[]
            }
        },
        methods:{
            // 获取上传状态
            select(e){
                console.log('选择文件:',e)
            },
            // 获取上传进度
            progress(e){
                console.log('上传进度:',e)
            },
            
            // 上传成功
            success(e){
                console.log('上传成功')
            },
            
            // 上传失败
            fail(e){
                console.log('上传失败:',e)
            }
        }
    }

案例一(只上传一张图片)

  
    
      
       
      
    
  


export default {
    data() {
      return {
        //图片
        imageValue:[],
      }
    },
    methods:{
      //图片上传
      select(e){
        const tempFilePaths = e.tempFilePaths;
        //获取图片临时路径
        const imgUrl=tempFilePaths[0]
        uni.uploadFile({
          //图片上传地址
          url: 'https://xxx.xxx.com/api/uploadpic/', 
          filePath: imgUrl,
          //上传名字,注意与后台接收的参数名一致
          name: 'imgUrl',
          //设置请求头
          header:{"Content-Type": "multipart/form-data"},
          //请求成功,后台返回自己服务器上的图片地址
          success: (uploadFileRes) => {
            console.log('uploadFileRes',JSON.parse(uploadFileRes.data));   
            //处理数据
            const path=JSON.parse(uploadFileRes.data)
            //赋值,前端渲染
            this.baseFormData.photo=path.imgUrl
          }
        });
      }, 
    }  
  }
图片展示

uni-file-picker文件选择上传

案例二(上传多张图片)

  
    
      
        
      
    
  



  export default {
    data() {
      return {
        imgURL:'',
        //图片
        imageValue:[],
      };
    },
    methods:{
      //图片上传
      select(e){
        const tempFilePaths = e.tempFilePaths;
        const imgUrl=tempFilePaths[0]
        uni.uploadFile({
          url: 'https://xxx.xxx.com/api/uploadpic2/', 
          filePath: imgUrl,
          name: 'imgUrl',
          header:{"Content-Type": "multipart/form-data"},
          success: (uploadFileRes) => {
            console.log('uploadFileRes',JSON.parse(uploadFileRes.data));
            let path=JSON.parse(uploadFileRes.data)
            //后端返回的地址,存入图片地址
            this.imageValue.push({
              url:this.imgURL+path.imgUrl,
              name:''
            })
            console.log('imageValue',this.imageValue)
          }
        });
      },
      //图片删除
      delIMG(e){
        console.log('456',e)
        const num = this.imageValue.findIndex(v => v.url === e.tempFilePath);
        this.imageValue.splice(num, 1);
      }
    },
    onLoad() { 
      //全局定义的图片访问地址前缀
      this.imgURL=this.$imgURL
    }
  }

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/5bbb281f7a.html