2015-02-23 18 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