Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

java - Get Web App root from Spring Controller

I am trying to write an uploaded multipart file to the filesystem. I have a directory called audio which sits in the root of my web application (not inside WEB-INF, but beside it, to it's publicly accessible like css and javascript).

I want to write the uploaded file to that directory but I can't seem to get the path I need. I thought getting a ServletContext() then using realPath() may work, but I don't have a reference to ServletContext through a Spring controller. Thanks for any hep

@RequestMapping(value="/uploadSample")
public ModelAndView upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile f) {

    if (f == null) {
        return new ModelAndView("upload", "msg", "The file is null.");
    }
    try {
        // I need to set AUDIO_PATH to <webAppRoot>/audio
        FileOutputStream file = new FileOutputStream(AUDIO_PATH + "/" + f.getOriginalFilename());
        file.write(f.getBytes());
        file.close();
    }
    catch (FileNotFoundException ex) {
        Logger.getLogger(SampleUploadController.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch (IOException ex) {
            Logger.getLogger(SampleUploadController.class.getName()).log(Level.SEVERE, null, ex);
    }



   return new ModelAndView("upload", "msg", "File ( " + f.getOriginalFilename() + ") successfully uploaded.");
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get reference to ServletContext, your class can implement ServletContextAware

ServletContext is also accessible in the web application container under the bean name servletContext, so you can inject it like any other bean in Spring. This works even if you don't have a session, and dependency injection is the Spring way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...