Search code examples
http-redirectgroovygrails

Grails oddness when trying to download a file from a URL


I'm trying to automate firmware updates on some of my systems. So, I first download a firmware file from the vendors website, and then I want to upload this to my TFTP server ready for my devices to pick up the new firmware.

I am using the following code to do this:-

def initiateUpdate(){
    if(!downloadFirmware()){
        println "Firmware download failed"
        return false
    }
}   

def downloadFirmware(){
    String downloadURL = 'https://myvendor.com/firmware/fw1.bin'
    redirect(url: downloadURL)
    return true  
    }

And this all works nicely, and I get a fw1.bin in my downloads directory. But when I try to seamlessly upload it to my TFTP server, it's breaking the firmware download somehow. i.e. If I now add :-

def initiateUpdate(){
    if(!downloadFirmware()){
        println "Firmware download failed"
        return false
    }
    if(!uploadFirmware()){
        print "Firmware upload failed"
        return false
    }
}   

def downloadFirmware(){
    String downloadURL = 'https://myvendor.com/firmware/fw1.bin'
    redirect(url: downloadURL)
    return true  
    }

def uploadFirmware(){
    String home = System.getProperty("user.home");
    def file=home + "\\Downloads\\fw1.bin"

    //  Now do the TFTP upload

    }

When I do the initiateUpdate, it doesn't download the file anymore, it arrives at the uploadFirmware section and fails as there is no file to upload.

I think I'm misunderstanding how the redirect works, so any pointers as to what I'm doing wrong, or a better way of doing it would be gratefully received.


Solution

  • You must use some some sort of http client to download the file from a remote location and save it on your server's disk. You can not do it with redirects inside the browser.

    What I mean can look like so:

    def uploadFirmware(){
        String home = System.getProperty("user.home");
        File file = new File( home, "\\Downloads\\fw1.bin" )
        String url = 'https://myvendor.com/firmware/fw1.bin'
    
        file.withOutputStream{ it << new URL( url ).inputStream() }
    
        true    
    }