-1

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

4

1 回答 1

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>  

数据控制器

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>  
于 2013-01-11T14:59:31.547 回答