SpringMVC接收 / 发图片数据(完整代码)

业务需求:

        1.后端接收前端传来的一张图片进行存储到项目的一个目录中

        2.后端把项目的一个目录的一张图片发送给前端


业务实现(用户头像图片传递为例):

保存用户头像接口:

     /**
     * 保存用户头像
     */
    @PostMapping("/saveAvatar")
    @ApiOperation("用户头像上传接口")
    @Globallnterceptor()
    public ResponseEntity<ByteArrayResource> saveAvatar(@RequestBody MultipartFile imageFile, HttpSession session) {
        // 获取用户id(文件"userId"来命名) 
        String userId = SessionUtil.getUserFromSession(session).getUserId();
        // 获取文件后缀
        String fileSuffix = StringUtil.getFileSuffix(Objects.requireNonNull(imageFile.getOriginalFilename()));
        userInfoService.saveAvatar(userId + fileSuffix, imageFile);
        return null;
    }

    /**
     * 获取文件的后缀
     */
    public static String getFileSuffix(String fileName) {
        Integer index = fileName.lastIndexOf(".");
        if (index == -1) {
            return "";
        }
        String suffix = fileName.substring(index);
        return suffix;
    }

保存用户头像Service:

@Override
    public void saveAvatar(String imgName, MultipartFile imageFile) {
        try {
            File destinationDir = new File(Constants.DESTINATION_PATH);
            if (!destinationDir.exists()) {
                boolean mkdirs = destinationDir.mkdirs();
                if (mkdirs){throw new BusinessException(AVATAR_INPUT_FALSE);}
            }
            // 根据原始文件名构建目标文件路径
            String destFilePath = Constants.DESTINATION_PATH + imgName;

            // 将文件复制到目标路径
            File destFile = new File(destFilePath);
            FileCopyUtils.copy(imageFile.getBytes(), destFile);
        } catch (IOException e) {
            throw new BusinessException(AVATAR_INPUT_FALSE);
        }
    }

这里要注意的是:当new File()的参数要传入的是相对路径的时候,我们的路径要从项目的根路径开始写,不是常规意义上的相对路径(../那类),具体看下方例子:

 


发送图像接口

    /**
     * 获取用户头像
     */
    @GetMapping ("getAvatar")
    @ApiOperation("头像获取接口")
    @Globallnterceptor()
    public ResponseEntity<ByteArrayResource> getAvatar(HttpSession session) {
        try {
            String userId = SessionUtil.getUserFromSession(session).getUserId();
            // ByteArrayResource 封装图片数据
            ByteArrayResource resource = userInfoService.getAvatar(userId);
            if (resource == null){return null;}
            // 设置响应头部信息
            HttpHeaders headers = new HttpHeaders();
            // 根据实际图片类型设置 MIME 类型
            headers.setContentType(MediaType.IMAGE_JPEG);
            // 返回带有图片数据的 ResponseEntity
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            throw new BusinessException("获取用户头像失败,请联系后台人员");
        }
    }

发送图像Service

@Override
    public ByteArrayResource getAvatar(String imgName) {
        try {
            // 从文件或其他数据源加载图片数据
            File imageFile = new File(Constants.DESTINATION_PATH + imgName + ".jpg");
            if (!imageFile.exists()){return null;}
            byte[] imageData = Files.readAllBytes(imageFile.toPath());
            // 创建 Resource 对象
            return new ByteArrayResource(imageData);
        } catch (IOException e) {
            throw new BusinessException(AVATAR_OUTPUT_FALSE);   
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学徒630

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值