[英]How to upload images in src/main/webapp/resources with spring MVC
I'm trying to upload an image with spring MVC in src/main/webapp/resources to display it in an img tag ( <img src="<c:url value="/resources/images/image.jpg" />" alt="image" />
) in my jsp. 我正在尝试使用src / main / webapp / resources中的spring MVC上传图像以在img标签中显示它(
<img src="<c:url value="/resources/images/image.jpg" />" alt="image" />
)放在我的jsp中。 I have this controller : 我有这个控制器:
@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.";
}
}
(...)
}
How do I build the rootPath
to have an absolute path of my system like this : C:/absolute/path/to/webapp/resources
or /absolute/path/to/webapp/resources
? 如何构建
rootPath
以使系统具有如下绝对路径: C:/absolute/path/to/webapp/resources
或/absolute/path/to/webapp/resources
?
I would say it is not good idea. 我会说这不是一个好主意。 In fact
src
folder does not exist. 实际上
src
文件夹不存在。 The resources are moved on compile. 资源在编译时移动。
Moreover it's not good to place uploaded under web root. 此外,将上传的文件放在网络根目录下也不好。 First because on restart the web root could be replaced with a new structure from WAR and because of security reasons.
首先,由于安全原因,重新启动Web根目录可以使用WAR中的新结构。 You get a potential hole letting something to be uploaded in the place where it could be run.
您有一个潜在的漏洞,可以将某些内容上传到可以运行的地方。
Instead define an upload path property and use it to store uploaded files and download them if necessary. 而是定义一个上载路径属性,并使用它存储上载的文件并在必要时下载它们。
UPDATE: 更新:
@Value("${myUploadPath}")
private String upload;
and specify property in eg application.properties or as JVM argument on start 并在例如application.properties中指定属性,或者在启动时将其指定为JVM参数
-DmyUploadPath="C:/absolute/path/to"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.