Jason
Jason

Reputation: 11363

Image upload to filesystem in Grails

I'm implementing a file upload functionality to a web-app in Grails. This includes adapting existing code to allow multiple file extensions. In the code, I've implemented a boolean to verify that the file path exists, but I'm still getting a FileNotFoundException that /hubbub/images/testcommand/photo.gif (No such file or directory)

My upload code is

def rawUpload = {       
    def mpf = request.getFile("photo")
    if (!mpf?.empty && mpf.size < 200*1024){
        def type = mpf.contentType
        String[] splitType = type.split("/")

        boolean exists= new File("/hubbub/images/${params.userId}")

        if (exists) {
            mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
        } else {
            tempFile = new File("/hubbub/images/${params.userId}").mkdir()
            mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
        }

    }
}

I'm getting the exception message at

if (exists) {
        mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}

So, why is this error happening, as I'm simply collatating an valid existing path as well as a valid filename and extension?

Upvotes: 3

Views: 1138

Answers (1)

Igor Artamonov
Igor Artamonov

Reputation: 35961

Why do you think that convertation of File object to Boolean returns existence of a file?

Try

    File dir = new File("/hubbub/images/${params.userId}")
    if (!dir.exists()) {
        assert dir.mkdirs()
    }
    mpf.transferTo(new File(dir, "picture.${splitType[1]}"))

Upvotes: 5

Related Questions