Hibernate:将保存在PostgreSQL数据库中的文件下载为bytea

时间:2015-02-23 14:57:59

标签: spring hibernate postgresql

我正在使用Spring-MVC应用程序,我将数据库中的文档保存为bytea。我能够成功将其保存到数据库中。现在我想在文件中以bytea的形式检索存储在PostgreSQL列中的数据。我也保存文件名,所以我可以给出相同的fileName,用户可以下载。我有代码下载一个有效的普通文件,但我不知道如何将bytea列作为文件,以便用户可以下载它。

这是代码: 附件模型:

@Entity
@Table(name = "attachments")
public class Attachment {


    @Id
    @Column(name="attachid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "attach_gen")
    @SequenceGenerator(name = "attach_gen",sequenceName = "attach_seq")
    private int attachid;

    @Column(name = "filename")
    private String fileName;

    @Column(name = "uploaddate")
    private Timestamp fileUploadDate;


    @Column(name = "attachmentdata")
    private byte[] attachment;

    // getters and setters ommitted
}

控制器代码到现在为止下载:

  @RequestMapping(value = "/download/attachment/{attachid}",method = RequestMethod.GET)
    public void getAttachmenFromDatabase(@PathVariable("attachid") int attachid, HttpServletResponse response){
        response.setContentType("application/pdf");
        try {

            // Below object has the bytea data, I just want to convert it into a file and send it to user. 
            Attachment attachment = this.attachmentService.getAttachmenById(attachid);

           // FileInputStream inputStream = new FileInputStream(sourcePath);
            //org.apache.commons.io.IOUtils.copy(inputStream,response.getOutputStream());

            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用Spring的FileCopyUtils来提供帮助。

    response.setHeader("Content-Disposition", "inline; filename=\""+ attachment.getFileName() +"\"");
    response.setContentLength(attachment.getAttachment().length);

    FileCopyUtils.copy(attachment.getAttachment(), response.getOutputStream());

Content-Disposition可以是inlineattachment,具体取决于您是希望浏览器内嵌显示内容还是强制下载。

从安全角度来看,您应该提供来自其他域(不是子域)的内联用户上传内容,例如exampleusercontent.com www.example.com,并使用反XSS安全标头,尤其是{{ 1}}

您还应该从上传的JPEG中擦除任何位置元数据。