2015-02-23 42 views
1

我正在使用Spring MVC应用程序,在该应用程序中将文档以字节形式保存在数据库中。我能够成功地将它保存到数据库中。现在我想以文件形式检索存储在PostgreSQL列中的数据作为bytea。我也保存文件名,所以我可以给相同的文件名,用户可以下载。我有代码来下载一个正常的文件,但我不知道如何将bytea列作为文件,以便用户可以下载它。休眠:将保存在PostgreSQL数据库中的文件下载为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

你可以使用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安全头,尤其是X-Content-Type-Options: nosniff

你也应该擦来自上传JPEG的任何位置元数据。

+0

谢谢你,这个看起来不错,明天会试试,让你知道并接受你的答案一旦完成,你可以请检查这个相关的问题,这将是超棒的,谢谢。 http://stackoverflow.com/questions/28674790/hibernate-single-out-a-column-containing-binary-data-which-shouldnt-be-loaded – 2015-02-23 20:31:29

+0

@WeareBorg你需要使用one2one关系w文件数据或者在该属性上使用javassist和延迟加载。我已经看到了SO之前的答案,但现在找不到它 – 2015-02-23 20:33:39

+0

是的,我正在寻找专门针对该属性的延迟加载,但我找不到它。如果你有幸找到它,请告诉我,现在就试试你的解决方案。 – 2015-02-24 07:47:52