Uploading a file, Spring MVC + CloudBees

半城伤御伤魂 提交于 2019-12-25 16:42:39

问题


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.


回答1:


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,..-.

  • Bees Shop ClickStart
  • Amazon S3 ClickStart

More info here.



来源:https://stackoverflow.com/questions/21590659/uploading-a-file-spring-mvc-cloudbees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!