4

Can anyone help me how to download an image from url in grails. Currently I am using the following code, but it is saving in current folder of the application. I want to download browser specific folder(like default folder which we download some file from web or saveAS)

 def imageDownload() {
            //imageURL = "http://www.google.com/images/logo.png"
    String fullPath = params.imageURL  

    String baseName = FilenameUtils.getBaseName(fullPath);
    String extension = FilenameUtils.getExtension(fullPath);
    def fileName = baseName+"."+extension

        def fileDoc = new File(fullPath);
    def webUtils = WebUtils.retrieveGrailsWebRequest()

    def response = webUtils.getCurrentResponse()

    response.setContentType("application/png")
    response.setHeader "Content-disposition", "attachment; filename=\"${fileName}\"";

    def file = new FileOutputStream(fullPath.tokenize("/")[-1])
            def out = new BufferedOutputStream(file)
            out << new URL(fullPath).openStream()
            out.close()

redirect(action: "imageDetails", params:params)
}

Need help, Thank you.

3 Answers3

4
def downloadImage = {
    def fileURL = "http://www.google.com/images/logo.gif"
    def thisUrl = new URL(fileURL);
    def connection = thisUrl.openConnection();
    def dataStream = connection.inputStream

    response.setContentType("application/octet-stream")
    response.setHeader('Content-disposition', 'Attachment; filename=logo.gif')
    response.outputStream << dataStream
    response.outputStream.flush()
}
Henk
  • 176
  • 1
  • 7
1

you can do it easily with a few groovy tricks:

URL urlCont = new URL(imageURL);
InputStream inStream = new BufferedInputStream(urlCont.openStream());
byte[] bytes = IOUtils.toByteArray(inStream);
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
0
       def download() {

        String fullPath = params.imageURL
        String baseName = FilenameUtils.getBaseName(fullPath);
        String extension = FilenameUtils.getExtension(fullPath);
        def fileName = baseName+"."+extension

        def webUtils = WebUtils.retrieveGrailsWebRequest()  
        def response = webUtils.getCurrentResponse()
        response.setContentType("application/png")
        response.setHeader "Content-disposition", "attachment; filename=\"${fileName}\"";
        def outputStream = response.getOutputStream()

        URL url = new URL(fullPath);
        InputStream is = new BufferedInputStream(url.openStream());
        byte[] buffer = new byte[1024];
        int length=0;
        while (-1!=(length=is.read(buffer)))
        {
           outputStream.write(buffer, 0, length);
        }
        outputStream.close();
        is.close();     
}

Thats all I am using..It is downloaded successfully...