2017-07-27 82 views
0

我試圖用src/main/webapp/resources中的spring MVC上傳一個圖像,將它顯示在我的jsp的img標籤(<img src="<c:url value="/resources/images/image.jpg" />" alt="image" />)中。我有這樣的控制器:如何使用spring MVC上傳src/main/webapp/resources中的圖像MVC

@Controller 
public class FileUploadController implements ServletContextAware { 
    private ServletContext servletContext; 
    private String rootPath; 

    @RequestMapping(value = "/uploadSingleFile", method = RequestMethod.GET) 
    public ModelAndView uploadSingleFileFormDisplay() { 
     return new ModelAndView("uploadSingleFile"); 
    } 

    @RequestMapping(value = "/uploadSingleFile", method = RequestMethod.POST) 
    public @ResponseBody String uploadSingleFileHandler(@RequestParam("file") MultipartFile file) { 
     String filename = file.getOriginalFilename(); 

     rootPath = servletContext.getRealPath("/") + "resources/uploads"; 

     if (!file.isEmpty()) { 
      try { 
       Document document = new Document(); 
       Image image = new Image(); 
       byte[] bytes = file.getBytes(); 

       BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(
        rootPath + "/" + filename 
       ))); 
       stream.write(bytes); 
       stream.close(); 

       return "You successfully uploaded " + filename + "!"; 
      } catch (Exception e) { 
       return "You failed to upload " + filename + " => " + e.getMessage(); 
      } 
     } else { 
      return "You failed to upload " + filename + " because the file was empty."; 
     } 

    } 
(...) 
} 

如何建立rootPath有我的系統中像這樣的絕對路徑:C:/absolute/path/to/webapp/resources/absolute/path/to/webapp/resources

回答

2

我會說這不是個好主意。其實src文件夾不存在。資源在編譯時移動。

此外,在web根目錄下上傳並不好。首先,因爲在重新啓動時,Web根目錄可能會被來自WAR的新結構替代,並且因爲安全原因。您可能會在可能運行的地方上傳某些內容。

取而代之,定義一個上傳路徑屬性,並用它來存儲上傳的文件並在必要時下載它們。

UPDATE:

@Value("${myUploadPath}") 
private String upload; 

並指定例如屬性application.properties或作爲啓動JVM參數

-DmyUploadPath="C:/absolute/path/to" 
+0

如何定義上傳路徑屬性? – simslay

+0

答案已更新 – StanislavL