2014-02-05 69 views
0

我已經在本地Tomcat的服務器上工作過,現在我剛剛部署了我的應用程序到CloudBees。 除了上傳文件到服務器的目錄外,一切都很好。上傳文件,Spring MVC + CloudBees

我有這樣一段代碼在我的控制器,這爲我工作在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"); 
} 

我不知道,如果這條線工作正常:

request.getSession().getServletContext().getRealPath("/") 

我m確定文件夾被創建,因爲我已經在我的eclipse項目中手動添加了它們。我還在提取到CloudBees之前手動添加了一些文件到這些文件夾,並且可以訪問這些文件,但是當我嘗試使用上述代碼上載文件時,它不起作用。

+0

我發現了一件事...我不確定如果作品返回這一行:/mnt/genapp/apps/7c7c897e/staxcat/install/webapp.war/resources/pdf/Facebook/有沒有辦法將文件添加到解壓縮到war文件的應用程序中? –

回答

1

文件系統在雲上並不是永久存在的,因此,以與在硬盤上相同的方式將文件上傳到文件系統並不是一個好習慣。

重新部署/向外擴展的應用程序將從一個不同的節點開始,因此您不應該在那裏存儲文件。我們建議使用amazon S3(或類似的文件存儲)進行存儲,並使用本地(「短暫」)文件系統作爲臨時緩存。

您可以使用System.getProperty(「java.io.tempDir」)獲取配置的本地臨時數據。

CloudBees還提供了兩個不同的示例,可幫助您將文件上傳到Amazon S3 - 您還可以使用Dropbox,Google Drive,..-。

更多信息here