Reputation: 16367
I am new to grails.I am doing web application that uploads the image from client side and it stores that in server.
My Gsp code is:
<g:uploadForm action="saveImage">
<input type="file" name="image">
<input type="submit" value="Submit">
</g:uploadForm>
My saveImage action in controller is:
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 upload some other files like text files it throws Exception.For that i want to check the file Extension and I want to use If loop that ensures the uploaded file is image file or not.But i dont know how to find the file extension in grails.
Is there any other way to upload images in grails application.It has to accept only image files.
can anyone provide help?
thanks.
Upvotes: 3
Views: 7195
Reputation: 3191
You can use Files.probeContentType(filePath) to determine file type
Upvotes: 0
Reputation: 21
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
Upvotes: 2
Reputation: 485
There is a small problem with file.getContentType()
. The way Windows and other systems handle it differ.
For example a .csv file will be text/plain
in other systems, but application/vnd.ms-excel
on Windows.
Upvotes: 1
Reputation: 548
Okay, this is really late. But what I found the best solutions (as extensions don't really say something about the content) was to use file.getContentType()
...
E.g., for jpeg images the return value will be a string image/jpeg
that you can easily test. Same for other file formats (png, gif, ...).
Hope this helps.
Upvotes: 0
Reputation:
Getting file extension from file.getOriginalFilename() works good.I think that is the better way.
Upvotes: 3
Reputation:
I dont know the following answer is a right way to find the extension of the file.I am also new to this.But this answer is working
Use file.getOriginalFilename() method.It returns a string like "test.jpg".Then you split the filename using tokenize method by ".".Then you take the last string element from the splitted list.That is extension of the file.Now you can do the remaining process.
Upvotes: 7