Upload image to grails

I am new to grails. I am making a web application that uploads an image from the client side and stores it on the server.

My Gsp Code:

<g:uploadForm action="saveImage"> <input type="file" name="image"> <input type="submit" value="Submit"> </g:uploadForm> 

My saveImage action in the controller:

 def saveImage={ def file = request.getFile('image') if (file && !file.empty) { file.transferTo(new java.io.File("image.jpg")) flash.message = 'Image uploaded' redirect(action: 'uploadImage') } } 

In this code, if I load some other files, such as text files, it throws an Exception. To do this, I want to check the file extension, and I want to use the If loop, which ensures that the downloaded file is an image file or not. But I do not know how to find the file extension in grails.

Is there any other way to upload images to grails app. It should only accept image files.

can anyone help?

thanks.

+3
source share
6 answers

I do not know that the following answer is the correct way to find the file extension. I am also new to this. But this answer works

Use the file.getOriginalFilename () method. It returns a string like "test.jpg". Then you split the file name with the tokenize method into "." Then you take the last element of the row from the split list. This is a file extension. Now you can complete the remaining process.

+7
source

Getting the file extension from the .getOriginalFilename () file works well. I think this is the best way.

+3
source
 if(params?.photo?.getContentType()=='image/jpeg' || params?.photo?.getContentType()=='image/gif' || params?.photo?.getContentType()=='image/png' || params?.photo?.getContentType()=='image/bmp' ) 

I think you can try this

+2
source

There is a small problem with file.getContentType() . The way you handle Windows and other systems is different.

For example, the .csv file will be text/plain on other systems, but application/vnd.ms-excel on Windows.

+1
source

Well, it's really late. But what I found, the best solutions (as extensions do not talk about content) was to use file.getContentType() ...

For example, for jpeg images, the return value will be the image/jpeg string, which you can easily check. The same goes for other file formats (png, gif, ...).

Hope this helps.

0
source

You can use Files.probeContentType (filePath) to determine the type of file

0
source

All Articles