首页 > 解决方案 > 如何获取文件列表

问题描述

我需要每次列出一个投资组合时,它都会返回该特定投资组合中存在的所有图像无效的

Photo Class
@Entity
public class Foto {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String nomeArquivo;

    @ManyToOne(cascade = CascadeType.MERGE)
    private Perfil autonomo;

    @Column(length = 5_000_000)
    private byte[] fotoByte;

    private String tipoArquivo;
}//Getters and Setters

自治服务

   @Autowired
    FotosRepository fotosRepository;

    @Autowired
    PerfisRepository perfisRepository;

    public List<byte[]> portfolio(int id){
        if (perfisRepository.existsById(id)) {
            return fotosRepository.findAllByAutonomoId(id).stream().map(f-> f.getFotoByte()).collect(Collectors.toList());
        }
        else {
            return null;
        }
    } //Getters and Setters

控制器

@GetMapping("/portfolio/fotos/{id}")
public ResponseEntity<List<byte[]>> getPortfolioAutonomo(@PathVariable int id) throws IOException {

    List<byte[]> result = autonomoService.portfolio(id);
    return ResponseEntity.status(200).body(result);
}

这就是我可以通过其 ID 获取 1 张照片的方式

 @GetMapping("/portfolio/{id}")
    public ResponseEntity getPortfolio(@PathVariable int id){
        Optional<Foto> anexoOptional = fotosRepository.findById(id);
        if (anexoOptional.isPresent()) {
            Foto anexo = anexoOptional.get();
            return ResponseEntity.status(200)
                    .header("content-type", anexo.getTipoArquivo())
                    .header("content-disposition", "filename=" + anexo.getNomeArquivo())
                    .body(anexo.getFotoByte());
 
        } else {
            return ResponseEntity.status(404).build();
        }
}

标签: javaspringspring-bootjpa

解决方案


代替

return fotosRepository.findAllByAutonomoId(id).stream().map(f-> f.getFotoByte()).collect(Collectors.toList());

你能试试吗

return fotosRepository.findAllById(id).stream().map(f-> f.getFotoByte()).collect(Collectors.toList());

如果这仍然不起作用,最好使用 @Query 实现。


推荐阅读