小编典典

如何使用Spring MVC在src / main / webapp / resources中上传图像

jsp

我正在尝试使用src / main / webapp / resources中的spring MVC上传图像,以<img src="<c:url value="/resources/images/image.jpg" />" alt="image" />在我的jsp
中的img标签()中显示它。我有这个控制器:

@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


阅读 297

收藏
2020-06-10

共1个答案

小编典典

我会说这不是一个好主意。实际上src文件夹不存在。资源在编译时移动。

此外,将上传的文件放在网络根目录下也不好。首先,由于安全原因,重新启动Web根目录可以使用WAR中的新结构。您有一个潜在的漏洞,可以将某些内容上传到可以运行的地方。

而是定义一个上载路径属性,并使用它存储上载的文件并在必要时下载它们。

更新:

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

并在例如application.properties中指定属性,或者在启动时将其指定为JVM参数

-DmyUploadPath="C:/absolute/path/to"
2020-06-10