Reputation: 1678
I want to create directory under one main root dir. I tried this code:
private static String UPLOADED_FOLDER = "/opt/";
@PostMapping
public ResponseEntity<StringResponseDTO> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, @RequestParam("id") Integer merchant_id) throws Exception {
InputStream inputStream = file.getInputStream();
String originalName = file.getOriginalFilename();
String name = file.getName();
String contentType = file.getContentType();
long size = file.getSize();
LOG.info("name: " + name);
LOG.info("contentType: " + contentType);
LOG.info("size: " + size);
try {
byte[] bytes = file.getBytes();
File newFile = new File(UPLOADED_FOLDER + merchant_id, file.getOriginalFilename());
LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the path
Files.write(newFile.toPath(), bytes);
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(new StringResponseDTO(originalName));
}
But I get exception:
2019-08-12 09:53:30,748 INFO [stdout] (default task-79) 09:53:30.747 [default task-79] INFO o.d.a.b.restapi.MerchantController - New file location: /opt/13/Screenshot 2019-08-01 at 14.58.59.png
2019-08-12 09:53:30,749 ERROR [stderr] (default task-79) java.nio.file.NoSuchFileException: /opt/13/Screenshot 2019-08-01 at 14.58.59.png
2019-08-12 09:53:30,750 ERROR [stderr] (default task-79) at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
Do I need to convert the number merchant_id
into String?
Upvotes: 0
Views: 57
Reputation: 612
I think exception is thrown because directory /opt/13
doesn't exists. Files.write
will create file, but no parent directories. Here is part of Files.write
documentation:
The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0.
Replace the following lines
File newFile = new File(UPLOADED_FOLDER + merchant_id, file.getOriginalFilename());
LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the path
Files.write(newFile.toPath(), bytes);
with
File directory = new File(UPLOADED_FOLDER, merchant_id.toString());
directory.mkdirs();
File newFile = new File(directory, file.getOriginalFilename());
LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the path
Files.write(newFile.toPath(), bytes);
Upvotes: 1