文件上传

1.前端

<el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
  <el-button size="small">
    上传
    <i class="el-icon-upload el-icon--right"></i>
  </el-button>
</el-upload>

// 上传图片
uploadImg() {
  this.$refs.cropper.getCropBlob(data => {
    let formData = new FormData();
    formData.append("avatarfile", data);
    uploadAvatar(formData).then(response => {
      if (response.code === 200) {
        this.open = false;
        this.options.img = process.env.VUE_APP_BASE_API + response.imgUrl;
        this.msgSuccess("修改成功");
      } else {
        this.msgError(response.msg);
      }
      this.$refs.cropper.clearCrop();
    });
  });
},

// 用户头像上传
export function uploadAvatar(data) {
  return request({
    url: '/system/user/profile/avatar',
    method: 'post',
    data: data
  })
}

2.后端

/**
 * 头像上传
 */
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
{
    if (!file.isEmpty())
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
        if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
        {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            // 更新缓存用户头像
            loginUser.getUser().setAvatar(avatar);
            tokenService.setLoginUser(loginUser);
            return ajax;
        }
    }
    return AjaxResult.error("上传图片异常,请联系管理员");
}

通用上传类

/**
 * 通用上传请求
 */
@PostMapping("/common/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
    try
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", fileName);
        ajax.put("url", url);
        return ajax;
    }
    catch (Exception e)
    {
        return AjaxResult.error(e.getMessage());
    }
}
posted @ 2020-05-27 22:01  xl4ng  阅读(159)  评论(0编辑  收藏  举报