1.vue页面

          <img v-if="avatar && avatar.indexOf('http')==-1 && !imgs[0]" style="width: 50%;height: 50%;border-radius: 0%;" :src="remoteUrl + avatar" @click="upload" />
          <img v-else-if="imgs[0]" :src="imgs[0]" width="100px" height="100px"  @click="deleteImg(0)"/>
          <svg-icon v-else style="width: 50%;height: 50%;" icon-class="picture" @click="upload"/>
          <input type="file" id="upload" style="display:none;" ref="upload" @change="changeimg" accept="image/*">

  

    upload () {
      let uploadbtn = this.$refs.upload
      uploadbtn.click()
    },
    deleteImg:function(index){
      this.imgs.splice(index,1);
      let uploadbtn = this.$refs.upload
      uploadbtn.click()
    },
    async changeimg (e) {
      this.file=e.target.files[0]
      var localFile = e.target.files[0];
      var reader = new FileReader();
      var content;
      var current=this;
      let formData=new FormData()
      formData.append('imgUploadFile', this.file)
      uploadImg(formData).then((response) => {
      })
      reader.onload = function(event) {
        content = event.target.result;
        current.imgs.push(content);  //获取图片base64代码
        this.overlay = true
      }
      reader.onerror = function(event) {
        qdMessage({
          message: 'error',
          type: 'error',
          duration: 3 * 1000
        })
      }
      content = reader.readAsDataURL(localFile,"UTF-8");
    },

  2.后端实现

    @PostMapping(value = "uploadImg")
    @ApiOperation(value = "更换头像", notes = "注册成功返回token")
    public ResultJson<String> uploadImg(MultipartHttpServletRequest mRequest) throws ParseException {
        User user=userService.getCurrentUser();
        MultiValueMap<String, MultipartFile> multiMap = mRequest.getMultiFileMap();
        Set<String> keys = multiMap.keySet();//遍历文件
        if (keys.size() > 0) {
            //String rootPath = mRequest.getSession().getServletContext().getRealPath("/");
            String path = "Upload/user/" + user.getId() + "/";
            File folder = new File(uploadPath + path);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            for (String key : keys) {
                //Upload
                MultipartFile file = multiMap.getFirst(key);
                if (!file.isEmpty()) {
                    if (key.equals("imgUploadFile")) {//上传的图片
                        //Upload
                        {//删除以前的图片
                            if (user.getImgPath() != null && !user.getImgPath().equals("")) {
                                File oldFile = new File(uploadPath, user.getImgPath());
                                if (oldFile.exists()) {
                                    oldFile.delete();
                                }
                            }
                        }
                        {//保存图片
                            String uuid = UUID.randomUUID().toString();
                            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));//获取文件类型
                            user.setImgPath(path + uuid + suffix.toLowerCase());
                            File dest = new File(uploadPath + user.getImgPath());
                            try {
                                file.transferTo(dest);
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        userService.updateById(user);
        return ResultJson.ok();
    }

  

posted on 2021-05-14 17:11  北边那座城  阅读(276)  评论(0编辑  收藏  举报