解析pdf文件并使用grails将数据存储到数据库中

时间:2013-01-11 14:30:29

标签: web-applications grails

我们有一个URL可以下载pdf文件。 问题是我们有一个输入文本字段,我们提供URL,我们有一个提交按钮。如果我们点击提交按钮然后下载相关文件并解析并存储在数据库中。

1 个答案:

答案 0 :(得分:3)

域类

class Data {  
    byte[] pdfFile  

    static mapping = {  
        pdfFile sqlType:'longblob'      //use mysql  
    }  

    static constraints = {  
        pdfFile nullable:true  
    }  
} 

gsp视图将url提交给控制器,例如 getFile.gsp

<g:form url="[action:'savePdf',controller:'data']" >  
       <g:textField name="externalUrl" >  
       <g:submitButton name="submit" value="Submit" />  
</g:form>  

<强> DataController类

class DataController {
    def savePdf() {                                  //save pdf file into database  
        def url = params.externalUrl           // for example:'http://moodle.njit.edu/tutorials/downloading_moodle.pdf' 

        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[10240000]              //pdf file size limited to 10M  
        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  
    }  
}

要触发renderPdf()方法,请在另一个gsp视图中添加一个链接,假设 render.gsp

<a href="${createLink(uri:'/data/renderPdf/'+dataInstance.id)}">pdf file</a>  
相关问题