0
点赞
收藏
分享

微信扫一扫

如何简单实现移动端APP扫码上传图片到PC端

看过我上一篇博客如何简单实现移动端APP扫码登录PC客户端_wx65efb457e87a1的技术博客_51CTO博客的朋友,应该能发现,其实实现移动端APP扫码上传图片到PC端的功能跟上一篇博客的功能类似,可以举一反三。

老规矩,先上图

如何简单实现移动端APP扫码上传图片到PC端_二维码

看过这张泳道图,脑海里应该就有思路了,下面简单介绍一下。

1、PC端申请图片上传二维码,与前面类似,调用接口申请二维码,轮询接口获取已上传图片ID。

handleUploadWithMobile(){
  if(this.token != undefined && this.token != null && this.token != ''){
    return;
  }else{
    qrupload().then(res=>{
      const result = res.data;
      if(result.code == 200){
        this.qrimg = result.data.img;
        this.token = result.data.qrtoken;
      }else{
        this.$Message.error({content:result.msg,duration:5});
      }
    });
  }

  this.timeInterval = setInterval(()=>{
    getRedisImg(this.token).then(res=>{
      let result = res.data;
      if(result.code == 200){
        let imglist = result.data.imglist;

        for(let a in imglist){
          let has = false;
          for(let b in this.fjlist){
            if(imglist[a].fjid == this.fjlist[b].fjid){
              has = true;
              break;
            }//for
          }//for
          if(!has){
            this.$emit("on-addimgid",{fjid:imglist[a].fjid,img:imglist[a].img,type:imglist[a].type}) ;
          }
        }
      }
    });
  },5000);
},

2、服务器生成二维码,返回base64

@ApiOperation("APP扫码上传图片-申请二维码")
@ResponseBody
@GetMapping("/qrupload-applyqr")
public RestResult requireQrCode(){
    String qrtoken = Utilities.createNewGUID() ;
    String qrtext = "ydgcxt#qrupload#"+qrtoken ;

    try{
        //写redis
        JSONObject jredis = new JSONObject() ;
        jredis.put("type","qrupload") ;
        jredis.put("qrtoken",qrtoken) ;
        jredis.put("qrtext",qrtext) ;

        redisUtil.set(qrtoken,jredis,1800) ;

        ByteArrayOutputStream os = new ByteArrayOutputStream() ;

        QRCodeUtil.encode(qrtext,os);

        String imgpic = new String(Base64.getEncoder().encode(os.toByteArray())) ;

        JSONObject ext = new JSONObject() ;
        ext.put("qrtoken",qrtoken) ;
        ext.put("img",imgpic) ;

        logger.info("qrupload-qrtext:"+qrtext);
        RestResult r = new RestResult(RestResult.CODE_SUCCESS,"") ;
        r.setData(ext);
        return r ;
    }catch (Exception ex){
        logger.error(ex.getMessage(),ex);
        RestResult r = new RestResult(RestResult.CODE_ERROR,"无法生成二维码") ;
        return r ;
    }
}

3、PC端展示二维码,不再赘述。

4、移动端登录扫码二维码,上传图片,这里需要先将图片资源存储到服务器,再将已上传的图片ID信息存储到redis中。

/**
 * 上传图片至redis
 * @param {Object} list // 扫码结果集合
 */
uploadFile(list){
    if(undefined == list[2] || null == list[2] || '' == list[2]){
       this.error({code: '201', message: '扫码失败'});
       return;
    }
    this.uploadToken = list[2];
    let pclist = [];
    // 打开相册多选图片
    plus.gallery.pick(
       success => {
          let files = success.files;
          // 遍历上传文件
          layerLoading();
          this.uploadFileSize = files.length;
          for (var i in files) {
             this.loadFile(files[i]);
          }
       },
       error => {
          // 取消
          this.start();
       }, {
          animation: true, // 是否显示系统相册文件选择界面的动画
          filter: 'image', // 文件类型
          multiple: true,  // 是否支持多选图片
          maximum: 5,     // 最多选择的图片数量
    
       }
    );
},
/**
 * 上传图片至服务器
 * @param {Object} path // 图片路径
 */
loadFile(path) {
    let that = this;
    let regular = /\.[a-z|A-Z]+$/;
    let rlist = path.match(regular, path);
    let tag = "_doc/temp.compress" + that.uploadFileIndex + rlist[0];
    that.uploadFileIndex++;
    plus.zip.compressImage({
          src: path,
          dst: tag,
          width: "800px" // 宽度缩小为原来的一半
       },
       function() {
          plus.io.resolveLocalFileSystemURL(tag, function(entry) {
             // 可通过entry对象操作test.html文件
             entry.file(function(file) {
                var fileReader = new plus.io.FileReader();
                fileReader.onloadend = function(evt) {
                   var filedata = evt.target.result;
                   file.close();
                   entry.remove();
                   // 定义vo
                   let uploadVO = {
                      file: filedata,
                      mulu: '未分组',
                      ywjm: '现场照片-'+path.substring(path.lastIndexOf('/') + 1, path.length), // 原文件名
                      wjdx: file.size, // 文件大小
                      wjlx: file.type
                   }
                   // 上传文件
                   http.request({
                      url: '/common/uploadFile',
                      data: uploadVO,
                      method: 'post'
                   }).then(res => {
                      console.log(JSON.stringify(res))
                      let pic = res.data.data
                      if (200 == res.data.code) {
                         let picture = {
                            fjid: pic.fjid,
                            scbz: 0,
                            type: pic.type
                         };
                         /* that.pagedata.piclist.push({
                            fjid: pic.fjid,
                            data: filedata,
                            path: path
                         }) */
                         that.uploadFiles.push(picture);
                      } else {
                         that.error({
                            code: '203',
                            message: '图片上传失败'
                         })
                      }
                   }).catch(e => {
                      console.log(JSON.stringify(e))
                      return e;
                   })
                }
                fileReader.readAsDataURL(file, 'utf-8');
             });
          }, function(e) {
             that.error({
                code: '204',
                message: e.message
             })
             console.log("Resolve file URL failed: " + e.message);
          });
       },
       function(error) {
          that.error(error);
          var code = error.code; // 错误编码
          var message = error.message; // 错误描述信息
          console.log("compress error code:" + code + ",message:" + message);
       });
}

/**
 * 监听图片是否上传完成
 * @param {Object} newval
 * @param {Object} oldval
 */
uploadFiles(newval, oldval){
    if(this.uploadFileSize != 0 && this.uploadFileSize == this.uploadFiles.length){
       let qrUploadPicVO = {
          qrtoken: this.uploadToken,
          imgidList: [],
       };
       for(let i in this.uploadFiles){
          qrUploadPicVO.imgidList.push(this.uploadFiles[i].fjid);
       }
       console.log(JSON.stringify(qrUploadPicVO));
       qrupload(qrUploadPicVO).then(res=>{
          layerEnd();
          if(200 == res.data.code){
             mui.alert('上传成功','提示','确定',e => {
                successful();
             },'')
          }else {
             that.error({
                code: '207',
                message: res.data.msg
             })
          }
       }).catch(e=>{
          layerEnd();
          that.error({
             code: '206',
             message: '图片上传失败'
          })
       });
    }
}

5、存储图片资源到服务器,写一个文件上传方法即可, 不贴代码了。

6、同步图片ID到redis。

/**
 * APP扫码上传图片,放进redis
 * @param qrUploadPicVO
 * @throws AppException
 * @throws Exception
 */
public void qrupload(QrUploadPicVO qrUploadPicVO) throws AppException,Exception {
    String qrtoken = qrUploadPicVO.getQrtoken();
    List<String> imgidList = qrUploadPicVO.getImgidList();
    JSONArray imgList = new JSONArray();

    if(qrtoken == null || "".equals(qrtoken)){
        throw AppException.createAppException(AppException.CODE_ERROR,"扫描二维码失败");
    }
    if(imgidList == null || imgidList.size() <= 0){
        throw AppException.createAppException(AppException.CODE_ERROR,"没有图片上传");
    }

    JSONObject ext = (JSONObject)redisUtil.get(qrtoken);
    if(ext == null){
        throw AppException.createAppException(AppException.CODE_ERROR,"二维码已失效");
    }

    for(String s : imgidList){
        JSONObject row = new JSONObject();
        row.put("imgid", s);
        imgList.add(row);
    }//for

    ext.put("imgidList", imgList);

    redisUtil.set(qrtoken,ext,1800);
}

7、PC端轮询请求获取图片,1中的定时器代码内容。

8、服务器接口查询redis图片内容返回。

@ApiOperation("APP扫码上传图片-获取redis中的APP上传的图片")
@ResponseBody
@GetMapping("/qrupload-getRedisImg")
public RestResult getRedisImg(@RequestParam String qrtoken){
    try{
        Object data = commonService.getRedisImg(qrtoken);
        RestResult r = new RestResult(RestResult.CODE_SUCCESS,"",data) ;
        return r ;
    }catch (AppException e){
        logger.error(e.getMessage(),e);
        RestResult r = new RestResult(RestResult.CODE_ERROR,e.getMessage()) ;
        return r ;
    }catch (Exception ex){
        logger.error(ex.getMessage(),ex);
        RestResult r = new RestResult(RestResult.CODE_ERROR,"服务器异常") ;
        return r ;
    }
}

欢迎指正讨论...

举报

相关推荐

0 条评论