lundi 23 février 2015

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

Aucun commentaire:

Enregistrer un commentaire