We are Borg
We are Borg

Reputation: 5313

Hibernate : Downloading a file saved in PostgreSQL database as bytea

I am working in a Spring-MVC application in which I am saving documents in the database as a bytea. I am able to successfully save it into the database. Now I would like to retrieve the data stored in PostgreSQL column as a bytea, in a file. I am also saving the filename, so I can give the same fileName and the user can download. I have code to download a normal file which works, but I don't know how to make the bytea column as a file so user can download it.

Here is the code : Attachments model :

@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 code till now to download :

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

Upvotes: 1

Views: 2588

Answers (1)

Neil McGuigan
Neil McGuigan

Reputation: 48287

You can use Spring's FileCopyUtils to help.

    response.setHeader("Content-Disposition", "inline; filename=\""+ attachment.getFileName() +"\"");
    response.setContentLength(attachment.getAttachment().length);

    FileCopyUtils.copy(attachment.getAttachment(), response.getOutputStream());

Content-Disposition can be inline or attachment, depending on whether you want the browser to display the content inline, or force a download.

From a security standpoint, you should serve inline user-uploaded content from a different domain (not subdomain), such as exampleusercontent.com for www.example.com and use the anti-XSS security headers, especially X-Content-Type-Options: nosniff

You should also wipe any location meta data from uploaded JPEGs.

Upvotes: 1

Related Questions