I have worked on local Tomcat's server and now I've just deployed my application to CloudBees. Everything works great apart from uploading a file to the server's directory.
I have such a piece of code in my controller, which worked for me on localhost:
@RequestMapping("/main/admin/upload")
public ModelAndView fileUploaded(
@ModelAttribute("uploadedFile") FileUpload uploadedFile,
final HttpServletRequest request,
final HttpServletResponse response, BindingResult result) {
InputStream inputStream = null;
OutputStream outputStream = null;
String pdfDirectory = uploadedFile.getPdfDirectory();
MultipartFile file = uploadedFile.getFile();
String fileName = file.getOriginalFilename();
try {
inputStream = file.getInputStream();
String pdfFileDirectory = request.getSession().getServletContext()
.getRealPath("/")
+ "resources\\pdf\\" + pdfDirectory + "\\";
File newFile = new File(pdfFileDirectory + fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView("redirect:/main/admin");
}
I'm not sure if this line is working correctly:
request.getSession().getServletContext().getRealPath("/")
I'm sure folders are created, because I have added them manually in my eclipse project. I've also added manually some files to these folders before extracting to CloudBees and these files are accessible, but when I try to upload file using above code, it doesn't work.
Filesystem is not persistent on the cloud, so it is NOT a good practice to upload files to the file system in the same way you on your hard disk.
Application being redeployed/scale-out will start on a distinct node, so you shouldn't store files there. We recommend to store using amazon S3 (or comparable file store) and use local ("ephemeral") filesystem as a temporary cache.
You can use System.getProperty("java.io.tempDir") to get the configured local temp.
CloudBees also provides two different examples which could help you to upload files to Amazon S3 -you can also use Dropbox, Google Drive,..-.
More info here.