mybatis 将二进制文件写入数据库保存,和文件下载

上传
public AjaxResult up(MultipartFile file) throws Exception {
    if (null == file) {
        return AjaxResult.error("文件为空");
    }
    byte[] imgbytes = file.getBytes();
 
    String filename = file.getOriginalFilename();
  
    logger.info("===filename===" + filename);
    Attachment attachment = new Attachment();
    attachment.setData(imgbytes);
    attachment.setFilename(filename);
    yqSelfService.addAttachment(attachment);
    return AjaxResult.success("成功", attachment.getId());

}

 

 
insert into  attachment (filename,`data`) values (#{filename},#{data,typeHandler=org.apache.ibatis.type.BlobTypeHandler})
 

文件下载

 @GetMapping(value = "/down/file")
    public AjaxResult importData(Long id, HttpServletResponse response) throws Exception {
        byte[] imgbytes = yqSelfService.findAttachment(id);
        if (null != imgbytes) {
            OutputStream out = response.getOutputStream();
            out.write(imgbytes);
        }
        return null;
    }
   public byte[] findAttachment(Long id) {
        try {
            Map map = yqSelfMapper.findAttachment(id);
            return (byte[]) map.get("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
        
    

    

前端展示

你可能感兴趣的:(Springboot,二进制文件保存)