前后端分离springboot+shiro+mybatis BASE64头像上传部分代码

//上传
@PostMapping("/upload_avatar")
public JSONObject uploadImage( MultipartHttpServletRequest request){
    logger.info("start call api /upload_avatar");
    byte[] data=null;
    try {
        List fileList = request.getFiles("file");
        MultipartFile file = fileList.get(0);
        InputStream inputStream = file.getInputStream();
        data = new byte[inputStream.available()];
        inputStream.read(data);
        inputStream.close();
        // 返回Base64编码过的字节数组字符串
        UpdateUserReq req=new UpdateUserReq();
        req = (UpdateUserReq) ReqInitUtil.init(req);
        req.setId(ShiroKit.getUserId());
        req.setAccountNumber(ShiroKit.getUser().getAccountNumber());
//java8 提供 java.util.Base64
        req.setImage(Base64.getEncoder().encodeToString(data));
        UpdateUserResp resp = userService.updateUser(req);
        if (SUCCESS_CODE.equals(resp.getRespCode())){
            return Response.SUCCESS.setData(resp).toJsonObject();
        }else {
            Response respon=new Response(false,"失败",resp);
            return respon.toJsonObject();
        }
    } catch (Exception e) {
        logger.error("uploadAvatar error is :", e);
        return Response.FAILED.toJsonObject();
    }
}
//下载
@RequestMapping("/load_avatar")
public void load(HttpServletResponse response) {
    try {
        logger.info("start call api /load_avatar");
        //设置发送到客户端的响应内容类型
        response.setHeader("Content-Type", "image/jpeg");
        FindUserAccountReq req=new FindUserAccountReq();
        req.setAccountNumber(ShiroKit.getUser().getAccountNumber());
        FindUserAccountResp resp= userService.findUserAccount(req);
        String image=resp.getUser().getImage();
        if(image!=null&&image.length()>0){
        byte[] bytes = Base64.getDecoder().decode(image)
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {// 调整异常数据
                bytes[i] += 256;
            }
        }
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(前后端分离springboot+shiro+mybatis BASE64头像上传部分代码)