How to upload images in src/main/webapp/resources

2019-08-21 09:03发布

问题:

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. 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 ?

回答1:

I would say it is not good idea. In fact src folder does not exist. 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. 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 e.g. application.properties or as JVM argument on start

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