spring - hibernate : Downloading a file saved in PostgreSQL database as bytea

标签 spring hibernate postgresql

我在一个 Spring-MVC 应用程序中工作,我将文档作为 bytea 保存在数据库中。我能够成功地将它保存到数据库中。现在我想在文件中检索存储在 PostgreSQL 列中的数据作为 bytea。我还保存了文件名,所以我可以提供相同的文件名,用户可以下载。我有下载正常文件的代码,但我不知道如何将 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
}

到目前为止要下载的 Controller 代码:

  @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();
        }
    }

最佳答案

您可以使用 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.comwww.example.com并使用反 XSS 安全 header ,尤其是 X-Content-Type-Options: nosniff

您还应该删除上传的 JPEG 中的所有位置元数据。

关于spring - hibernate : Downloading a file saved in PostgreSQL database as bytea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676595/

相关文章:

java - 使用 Spring 批处理处理大文件的最佳方法

java - spring如何使用多个数据库?

java - Grails、UUID、Postgresql、生成 View

java - 创建一个 HQL 查询,该查询将获取集合中的每个项目并进行比较

ruby-on-rails - Rails 测试数据库在地理列上获取错误的列类型

javascript - 使用 pg 管理从 nodejs 到 postgres 的许多连接

mysql - 如何在mysql服务器中设置用户的远程访问?

java - 使用带有嵌入式 Jetty 的 Spring-Boot 在 Camel rest-component 上配置 SSL

spring - Java 8 JPA Repository Stream 在 Postgresql 中逐行

java - 连接被拒绝 : connect Error in Java + Hibernate