我在一个 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
可以是 inline
或 attachment
,具体取决于您是希望浏览器内联显示内容,还是强制下载.
从安全的角度来看,您应该提供来自不同域(而非子域)的内联用户上传内容,例如 exampleusercontent.com
为 www.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/