convert CommonsMultipartFile to file - grails

I am using a plugin that uploads files as a CommonsMultipartFile. The upload works fine, but I am trying to use another plugin to read the files header (the mp3 header) but it will not take CommonsMultipartFile, only regular files. Is there a way to either convert the CommonsMultipartFile to a file or have some other work around. I've tried copying the file from where it gets uploaded from, but it doesn't seem to work. here is what i have so far:
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("files");
moveFile(file)
}
private moveFile(CommonsMultipartFile file){
def userId = getUserId()
def userGuid = SecUser.get(userId.id).uid
def webRootDir = servletContext.getRealPath("/")
def userDir = new File(webRootDir, "/myUsers/${userGuid}/music")
userDir.mkdirs()
file.transferTo( new File( userDir,file.originalFilename))
def myFile = new File( "/myUsers/${userGuid}/music/" + file.originalFilename)
AudioFile audioFile = AudioFileIO.read(file);
//AudioFile is expecting a file, not a CommonsMultipartFile
}
When i do this, though, i get this error:
groovy.lang.MissingMethodException: No signature of method: static org.jaudiotagger.audio.AudioFileIO.read() is applicable for argument types: (org.springframework.web.multipart.commons.CommonsMultipartFile) values: [org.springframework.web.multipart.commons.CommonsMultipartFile#10a531]
Thanks
jason

Your code copied MultiPart file to a File, but still used Multipart file for AudioFileIO.
It must be like:
private moveFile(CommonsMultipartFile file){
def userId = getUserId()
def userGuid = SecUser.get(userId.id).uid
def webRootDir = servletContext.getRealPath("/")
def userDir = new File(webRootDir, "/myUsers/${userGuid}/music")
userDir.mkdirs()
File myFile = new File( userDir,file.originalFilename)
file.transferTo(myFile)
//
// !!!!!! you have to pass myFile there
//
AudioFile audioFile = AudioFileIO.read(myFile)
}

Related

RestBuilder Plugin. How can I upload a file without creating a file?

Currently, I can upload files(exist) with Grails's RestBuilder.
However, I want to upload a file without creating a file .
I want to create binary data (= Text File) in a program and send it directly
Is it possible?
RestBuilder rest = new RestBuilder()
RestResponse resp = rest.post(url){
contentType("multipart/form-data")
setProperty("dataFile",[filePath])// <- it can
setProperty("dataFile",[ byte[] or inputStream() or String ? ])// <- Is it possible?
}
'''
I'm sure you figured this out already, but you can just use a String reference or a byte[] just as you can use File instances for the multipart request using RestBuilder. It should 'just work' e.g.
RestBuilder rest = new RestBuilder()
RestResponse response = rest.post(url) {
contentType 'multipart/form-data'
stringPart = 'hello' // String
bytePart = '68656c6c6f'.decode64() // byte[]
filePart = new File('/path/to/file.jpg') // File
}

Can config slurper parse methods with map as input variable

I am trying to parse a groovy file using config slurper like this .
fileContents = '''deployment {
deployTo('dev') {
test = me
}
}'''
def config = new ConfigSlurper().parse(fileContents)
The above code works because the deployto('dev') is simply accepting a string. But I add an extra parameter to it , it fails with this exception:
fileContents = '''deployment {
deployTo('dev','qa') {
test = me
}
}'''
def config = new ConfigSlurper().parse(fileContents)
It fails with the following exception :
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.util.ConfigSlurper$_parse_closure5.deployTo() is applicable for argument types: (java.lang.String, java.lang.String, script15047332444361539770645$_run_closure3$_closure10) values: [dev, postRun, script15047332444361539770645$_run_closure3$_closure10#6b8ca3c8]
Is there a way around reading this config file with extra args in a module?
You are almost there. In order to use list of values, please do the below change.
From:
deployTo('dev','qa')
To:
deployTo(['dev','qa'])
It would be:
def fileContents = '''deployment { deployTo(['dev','qa']) { test = me } }'''
def config = new ConfigSlurper().parse(fileContents)​

Trying to delete a uploaded file from directory file system

I have a web app that uploads files to file system and show them in a list. I am trying to delete the item with a button. I know I need to get the path of the directory file to be able to delete it and I believe this is where I am stuck:
def delete = {
def doc = Document.get(params.id)
def path = Document.get(path.id)
doc.delete(path)
redirect( action:'list' )
}
error I am getting: No such property: path for class: file_down.DocumentController Possible solutions: flash
It seems to me def path = Document.get(path.id) is wrong, in that case how do we find the path of a document ?
This is my upload method where I upload the files, assign it to a specific filesize, date, and fullPath( which is the uploaded folder)
def upload() {
def file = request.getFile('file')
if(file.empty) {
flash.message = "File cannot be empty"
} else {
def documentInstance = new Document()
documentInstance.filename = file.originalFilename
documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
documentInstance.fileSize = file.getSize() / (1024 * 1024)
documentInstance.company = Company.findByName(params.company)
if (documentInstance.company == null) {
flash.message = "Company doesn't exist"
redirect (action: 'admin')
}
else {
file.transferTo(new File(documentInstance.fullPath))
documentInstance.save()
redirect (action:'list', params: ['company': params.company])
}
}
}
I think you have an error in this line:
def path = Document.get(path.id)
You try to get path.id from the path variable you are just declaring.
I'm pretty sure that you mean
def path = new File(doc.fullPath)
path.delete() // Remove the file from the file-system
doc.delete() // Remote the domain instance in DB
Alternative:
class Document {
// Add this to your Document domain
def beforeDelete = {
new File(fullPath).delete()
}
}
and then you could just do this in your controller:
def delete = {
def doc = Document.get(params.id)
doc.delete() // Delete the domain instance in DB
redirect( action:'list' )
}

commonsMultipartFile trouble

Hi I have am trying to implement a file upload in my application where the file uploaded is parsed and an entry is created in the database using that information.
def save = {
def file = request.getFile("file");
def filename = file.getOriginalFilename();
def type = filename.split('\\.');
if(!file.isEmpty()){
if(type[1] == "properties"){
redirect(action:"parsePropertyFile", params:params);
}
}
}
def parsePropertyFile = {
println "\n"
println params.file;
println "\n";
def f = params.file;
println f;
def filename = f.getOriginalFilename();
println filename;
}
when I print out f this is output:
org.springframework.web.multipart.commons.CommonsMultipartFile#29d32df9
but when I try to call getOriginalFilename() on f I get the following error:
groovy.lang.MissingMethodException: No signature of method:
java.lang.String.getOriginalFilename() is applicable for argument types: () values: []
I also printed out file from the save function and the output of that is also:
org.springframework.web.multipart.commons.CommonsMultipartFile#29d32df9
so why am I getting the error?
Instead of redirecting, can you just call your another function? Redirect will issue an http redirect with the file as param with no need.
if(type[1] == "properties") {
parsePropertyFile(file)
}
And then:
private def parsePropertyFile(def file) {
String filename = file.getOriginalFilename();
...
}
In your parsePropertyFile action you aren't getting a File object, you're getting the String from params. Just like in your save action, you need to do
def f = request.getFile('file')
println f.getOriginalFilename()

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?
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]}"))

Resources