---
title: "How to upload file from web url and save it to database (Grails)"
author: "biomedinfo"
date: "2013-01-11T22:55:25Z"
tags: []
categories: ["编程语言"]
slug: "how-to-upload-file-from-web-url-and-save-it-to-database-grails"
draft: false
lastmod: "2013-01-11T23:12:07Z"
id: 1768592
url: "https://ned11.iteye.com/blog/1768592"
---

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>
```