【问题标题】:how to store and retrieve image files from database using springboot如何使用spring boot从数据库中存储和检索图像文件
【发布时间】:2022-01-02 20:01:14
【问题描述】:

我正在构建一个有角度的 springboot 应用程序,但我找到了很多方法来做到这一点,其中一些我真的不明白。 如何一次存储 1 个或多个图像并检索它们。

【问题讨论】:

    标签: database spring-boot spring-data-jpa blob


    【解决方案1】:

    您可以使用@Lob 在数据库中存储图像或任何文件。下面的例子展示了这种方法的简单实现

    @Entity
    @Table(name = "file")
    public class File {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(name = "uuid")
        private String uuid;
    
        @Column(name = "content_type")
        private String contentType;
    
        @Column(name = "extension")
        private String extension;
    
        @Lob
        @Column(name = "content", columnDefinition = "LONGBLOB")
        private byte[] content;
    }
    
    
    
    @Service
    public class FileService {
    private final FileRepository repository;
    
    @Autowired
    public FileService(FileRepository repository) {
        this.repository = repository;
    }
    
    @Transactional
    public StreamingResponseBody download(Long id, HttpServletResponse response) {
        final File file = repository.findById(id).orElseThrow(NotFoundException::new);
        return outputStream -> {
            String fileName = (file.getUuid() + file.getExtension()).trim();
            response.setContentType(file.getContentType());
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    
            outputStream.write(file.getContent());
            outputStream.flush();
        };
    }
    
    public FileDto create(MultipartFile multipartFile, boolean general) {
        String fileName = multipartFile.getOriginalFilename();
        String fileExtension = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf('.'));
        String uuid = UUID.randomUUID().toString();
        UserDto user = contextUtils.getPrincipal();
    
        File file = new File();
        file.setUuid(uuid);
        file.setContentType(multipartFile.getContentType());
        file.setExtension(fileExtension);
        file.setGeneral(general);
        file.setContent(multipartFile.getBytes());
        file.setId(repository.save(file).getId());
    
        return file;
    }
    

    }

    【讨论】:

    • 很抱歉,这背后的逻辑是什么,我很难理解这段代码
    猜你喜欢
    • 2011-03-21
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2016-05-27
    • 2013-06-17
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多