ITeye博客

How to upload file from web url and save it to database (Grails)

biomedinfo · 2013-01-11 22:55 · 编程语言 · Markdown

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>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。