asfarasiknow
asfarasiknow

Reputation: 325

Change file permissions in java

I want to convert the MultipartFile to File and upload this to specified directory on my ec2 instance. Here is the converter method.

 private fun convertMultiPartFileToFile(multipartFile: MultipartFile, name: String): File? {
        val file = multipartFile.originalFilename?.let { File(it) }
        try {
            log.info { file?.canWrite() } // logs 'false'
            log.info { file?.canExecute() } // logs 'false'
            file?.setExecutable(true) // still 'false'
            file?.setWritable(true) // still 'false'

            file.let {
                if (file != null) {
                    FileOutputStream(file).use { outputStream -> outputStream.write(multipartFile.bytes) }
                }
            }
        } catch (e: IOException) {
            throw RuntimeException(e)
        }

        return file
    } 

It works locally, but when I try this on my ec2 instance, I got the error

java.lang.RuntimeException: java.io.FileNotFoundException: file.png (Permission denied)

I guess it's because I do not have permission to write to specified file. How can I solve this if file?.setWritable(file) and file?.setExecutable(true) return false. I run the jar by java -jar path/to/jar

The setWritable method documentation says

     * @return  {@code true} if and only if the operation succeeded.  The
     * operation will fail if the user does not have permission to
     * change the access permissions of this abstract pathname.

How to get the access permissions to this abstract pathname then?

Upvotes: 0

Views: 571

Answers (1)

dan1st
dan1st

Reputation: 16486

MultipartFiles do not represent files on the file system while File represents a local file on your system. They are just data that's uploaded.

Hence, multipartFile.originalFilename does not give you the name of any file on your system (except a file with the same name "randomly" exists) but the name of the file the user uploaded (on their system).

If you want to access a MultipartFile as a File, you first need to save it as such:

val file=File("what/ever/file/you.want")//in the directory you want to upload it to
multipartFile.transferTo(file)
//it is now stored in file

This will copy the file to your system.

Upvotes: 1

Related Questions