Domain class:
class Data {
byte[] pdfFile
static mapping = {
pdfFile sqlType:'longblob' //use mysql
}
static constraints = {
pdfFile nullable:true
}
}
gsp view to submit the url to controller:
<g:form action="savePdf" >
<g:textField name="externalUrl" >
<g:submitButton name="submit" value="Submit" />
</g:form>
DataController:
def savePdf() { //save pdf file into database
def url = params.externalUrl
def localFile = new FileOutputStream('test.pdf')
localFile << new URL(url).openStream()
localFile.close()
def pdfFile = new FileInputStream('test.pdf')
byte[] buf = new byte [102400]
byte[] pdfData = new byte[9024000] //pdf file size limited to 1M
int len = pdfFile.read(buf, 0, 102400)
ByteArrayOutputStream bytestream = new ByteArrayOutputStream()
while(len > 0) {
bytestream.write(buf, 0, len)
len =pdfFile.read(buf, 0, 102400)
}
data.pdfFile = bytestream.toByteArray()
data.save()
}
def renderPdf() { //for pdf file download
def dataInstance = Data.get(params.id)
response.setContentType('application/pdf')
byte[] pdf = dataInstance?.pdfFile
response.outputStream << pdf
}
To trigger renderPdf() method, put a link in another gsp view:
<a href="${createLink(uri:'/data/renderPdf/'+dataInstance.id)}">pdf file</a>