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

本文介绍了一种使用Groovy将PDF文件从URL下载并保存到数据库的方法。具体步骤包括:通过URL获取PDF文件,将其读取为字节数组,并使用Grails ORM将数据保存到数据库中。此外,还提供了一个用于下载已保存PDF文件的控制器方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值