bhw1899
bhw1899

Reputation: 87

Can I write file to CentOS usr/share/files/ from a Spring boot application?

I am writing a file upload Spring boot application, everything except path is good to go. I tested on Window, it works well. But when I uploaded my war package to tomcat, the upload looks successfuly. But I can't find the file on my server anywhere.

private const val UPLOADED_FOLDER = "usr/share/nginx/html/"

@PostMapping("/upload.do")
    @ResponseBody
    fun singleFileUpload(@RequestParam("file") file: MultipartFile,
                         @RequestParam("path") path: String? = "",
                         redirectAttributes: RedirectAttributes): ResponseEntity<*> {
        if (file.isEmpty) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload")
            return ResponseEntity.ok("redirect:uploadStatus")
        }
        val pathRoot = UPLOADED_FOLDER + path
        try { // Get the file and save it somewhere
            val bytes = file.bytes
            val path: Path =
                    Paths.get(pathRoot + File.separator + file.originalFilename)
            Files.write(path, bytes)
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.originalFilename + "'")
        } catch (e: IOException) {
            e.printStackTrace()
        }
        fileCompressService.decompressTar(pathRoot, file.originalFilename)

        return ResponseEntity.ok("redirect:uploadStatus")
    }

Upvotes: 0

Views: 431

Answers (1)

Piotr P. Karwasz
Piotr P. Karwasz

Reputation: 16105

You use a relative path usr/share/nginx/html, which means your file is written in subdirectories of the server working directory. This might vary from server to server, but probably is $CATALINA_BASE. Use an absolute path /usr/share/nginx/html.

Remark: On a UNIX system you'll probably get permission denied, since /usr is only writable by root. Variable data should usually be written to /var.

Upvotes: 1

Related Questions