Подскажите пожалуйста, как в Spring реализовать чтение pdf файла из базы

В базе postgresql хранится pdf в типе byte, хранимой процедурой выбираю этот файл, но не получается реализовать его открытие.

@Entity
@Table
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(name = "qProcedure", procedureName = "get_files",
                parameters = {
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "pidndbook", type = Integer.class)
                })
})

public class FilesPdf {
    @Id
    private int id;
    private int idndbook;
    private String name;
    private byte[] pdf;

    public FilesPdf() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getIdndbook() {
        return idndbook;
    }

    public void setIdndbook(int idndbook) {
        this.idndbook = idndbook;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getPdf() {
        return pdf;
    }

    public void setPdf(byte[] pdf) {
        this.pdf = pdf;
    }
}
 



@Repository
public class FilesPdfDao {
    @Autowired
    private EntityManager em;

    @SuppressWarnings("unchecked")
    public List<FilesPdf> getPdf(Integer input) {
            StoredProcedureQuery q = this.em.createNamedStoredProcedureQuery("qProcedure");
            q.setParameter("pidndbook", input);
            List<FilesPdf> reviews = q.getResultList();
            return reviews;
    }
}




@RequestMapping("/file/{idndbook}")
@ResponseBody
public void show(@PathVariable("idndbook") int idndbook,
                 @RequestParam(required = false, defaultValue = "digitalskills.pdf") String fileName,
                 HttpServletResponse response) {

    //String folderPath = "/Users/ekaterina/Downloads/";
    List<FilesPdf> pdf = dao.getPdf(idndbook);
    
    if (fileName.indexOf(".pdf")>-1) response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=" +fileName);
    response.setHeader("Content-Transfer-Encoding", "binary");
    
    try {
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        FileInputStream fis = new FileInputStream( fileName);    //folderPath+fileName
        int len;
        byte[] buf = new byte[1024];
        while((len = fis.read(buf)) > 0) {
            bos.write(buf,0,len);
        }
        bos.close();
        response.flushBuffer();
    }
    catch(IOException e) {
        e.printStackTrace();

    }

}

Как из переменной pdf в контроллере вытащить этот тип byte и открыть в браузере?


Ответы (0 шт):