我尝试在src / main / webapp / resources中使用spring MVC上传图像,以便在我的jsp中的img标记(\033
)中显示它。我有这个控制器:
<img src="<c:url value="/resources/images/image.jpg" />" alt="image" />
如何构建@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
?
答案 0 :(得分:2)
我想说这不是个好主意。实际上src
文件夹不存在。资源在编译时移动。
此外,在网络根目录下上传是不合适的。首先,因为在重新启动时,可以使用WAR中的新结构替换Web根目录,并且由于安全原因。你可以在一个可以运行的地方上传一些东西。
而是定义上传路径属性,并使用它来存储上传的文件,并在必要时下载它们。
更新:
@Value("${myUploadPath}")
private String upload;
并在例如指定属性application.properties或作为启动时的JVM参数
-DmyUploadPath="C:/absolute/path/to"