springboot巧妙的处理图片

2022-11-10 21:51:10 浏览数 (1)

将图片插入mysql数据库

代码语言:javascript复制
  @PostMapping
  public R<Boolean> insert(@NotNull @RequestParam MultipartFile picture,String type) {
        try {
            QualityAnalysis qualityAnalysis=new QualityAnalysis();
            byte[] bytes = picture.getBytes();
            qualityAnalysis.setData(bytes);
            qualityAnalysis.setType(type);
            return success(this.qualityAnalysisService.save(qualityAnalysis));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success(null);
    }

浏览器展示图片

代码语言:javascript复制
  @RequestMapping(value = "/picture",method = RequestMethod.GET,produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] getPicture(Integer id){
        QualityAnalysis qualityAnalysis = this.qualityAnalysisService.getById(id);
        return qualityAnalysis.getData();
    }

浏览器下载图片

代码语言:javascript复制
  @GetMapping("/write")
    public void writeBpa(Long planId, HttpServletResponse response) {
        try {
            BpaBo bpaBo = this.planService.writeBpa(planId);
            // 清空response
//            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename="   URLEncoder.encode("bpa_out.dat", StandardCharsets.UTF_8));
            // 告知浏览器文件的大小
//            response.addHeader("Content-Length", Flux.just(bpaBo.getData().length()).toString());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(bpaBo.getData().getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

0 人点赞