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

Hibernate : Downloading a file saved in PostgreSQL database as bytea

我在 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
}

现在可以下载的控制器代码:

  @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,具体取决于您是希望浏览器内联显示内容,还是强制下载。

从安全的角度来看,您应该提供来自不同域(而非子域)的内联 user-uploaded 内容,例如 exampleusercontent.com 用于 www.example.com 并使用 anti-XSS安全 headers,尤其是 X-Content-Type-Options: nosniff

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