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:


       
       
 

 

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:

pdf file

 

你可能感兴趣的:(Grails,upload,database)