`
biomedinfo
  • 浏览: 24759 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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

阅读更多

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>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics