Reputation: 2019
I need to save image to a folder in my application. So far I have learned to save image into a database but I need to save it to a folder. How can I do this? Can anyone please help me on this please? here is my code below to save into database >>>
def upload={
def user = User.findById(1)
CommonsMultipartFile file = params.list("photo")?.getAt(0)
user.avatar = file?.bytes
user.save()
}
Upvotes: 1
Views: 4879
Reputation: 2019
I have solve this so easily as follows. You will have to import followings :
import org.apache.commons.io.FileUtils
import org.springframework.web.multipart.commons.CommonsMultipartFile
import org.springframework.web.multipart.*
Good luck who needs this >>>
def saveImageToFolder = {
String message = ""
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("userPhoto")
if(!f.empty) {
def usr = User.findByUsername(1)
if(!usr){
User user = new User()
user.username = params.username
user.avatarType = f.getContentType()
if(user.save()){
def userId = user.id
String username = user.username
String fileName = username + "." + f.getContentType().substring(6) // here my file type is image/jpeg
byte[] userImage = f.getBytes()
FileUtils.writeByteArrayToFile(new File( grailsApplication.config.images.location.toString() + File.separatorChar + fileName ), userImage )
message = "User Created Successfully."
}else{
message = "Can not Create User !!!"
}
}else{
message = "Username already exists. Please try another one !!!"
}
}
else {
message = 'file cannot be empty'
}
render(view: 'addUser', model:[message: message])
}
and in your config file paste this >>>
images.location = "web-app/images/userImages/" // after web-app/folder name/folder name and go on if you want to add other folder
Upvotes: 0
Reputation: 3080
You have only to copy the MutipartFile into web-app folder. This is how :
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("myfile");
String fileName = System.currentTimeMillis() + f.name
String destinationFileName = configService.getAbsoluteDocumentsPath() + fileName // We will put it on web-app/documents/xxxxx
f.renameTo(new File(destinationFileName))
//Save filename to database in
user.avatar = fileName
user.save()
And in configService I have that (used to calculate paths)
class ConfigService {
def grailsApplication
/**
* @return absolute path of documents
*/
def getAbsoluteDocumentsPath(){
def asolutePath = grailsApplication.mainContext.servletContext.getRealPath('documents')
return asolutePath.endsWith("/") ? asolutePath : asolutePath + "/"
}
}
EDIT To make sure that your request is an instance of MutipartHttServletRequest Add the following test
if(request instanceof MultipartHttpServletRequest) {
//Do stuff here
}
Don't forget to check the the encoding of the form in which you put the file input.
Upvotes: 2
Reputation: 633
Find below for the step wise implementation, I have added a GSP page with the uploadForm(it will have multipart form submission by default), and then a controller function to handle file save request, and a service method to save file in a specified directory:
Step1: Create a form for file upload:
<g:uploadForm name="picUploadForm" class="well form-horizontal" controller="<your-controller-name>" action="savePicture">
Select Picture: <input type="file" name="productPic"/>
<button type="submit" class="btn btn-success"><g:message code="shopItem.btn.saveProductImage" default="Save Image" /></button>
</g:uploadForm>
Step2: Then in your controller's savePicture action:
String baseImageName = java.util.UUID.randomUUID().toString();
// Saving image in a folder assets/channelImage/, in the web-app, with the name: baseImageName
def downloadedFile = request.getFile( "product.baseImage" )
String fileUploaded = fileUploadService.uploadFile( downloadedFile, "${baseImageName}.jpg", "assets/channelImage/" )
if( fileUploaded ){
// DO further actions, for example make a db entry for the file name
}
Step3: and in the file uploader service(User defined service with the name FileUploadService in this case):
def String uploadFile( MultipartFile file, String name, String destinationDirectory ) {
def serveletContext = ServletContextHolder.servletContext
def storagePath = serveletContext.getRealPath( destinationDirectory )
def storagePathDirectory = new File( storagePath )
if( !storagePathDirectory.exists() ){
println("creating directory ${storagePath}")
if(storagePathDirectory.mkdirs()){
println "SUCCESS"
}else{
println "FAILED"
}
}
// Store file
if(!file.isEmpty()){
file.transferTo( new File("${storagePath}/${name}") )
println("Saved File: ${storagePath}/${name}")
return "${storagePath}/${name}"
}else{
println "File: ${file.inspect()} was empty"
return null
}
}
Upvotes: 4