Search code examples
grailsgrails-controller

convert CommonsMultipartFile to file


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


Solution

  • 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) 
    }