我試圖用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
?
如何定義上傳路徑屬性? – simslay
答案已更新 – StanislavL