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
157 views
in Technique[技术] by (71.8m points)

java - how to get getServletContext() in spring mvc Controller

I need to upload images in my project. How to get the upload path in SpringMVC. The path is;

/home/cme/project/eclipse/workspace_12_11/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fileUploadTester/upload

The following error;

The method getServletContext() is undefined for the type HomePageController

appears when I use this code;

String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

My code is

public ModelAndView UploadPhoto(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
 final String UPLOAD_DIRECTORY = "upload";
 final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
 final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
 final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

 String value[] = new String[10];
 int i = 0;

 // checks if the request actually contains upload file
 if (!ServletFileUpload.isMultipartContent(request)) {
  PrintWriter writer = response.getWriter();
  writer.println("Request does not contain upload data");
  writer.flush();
  return; //here is error This method must return a result of type ModelAndView
 }

 DiskFileItemFactory factory = new DiskFileItemFactory();
 factory.setSizeThreshold(THRESHOLD_SIZE);
 factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

 ServletFileUpload upload = new ServletFileUpload(factory);
 upload.setFileSizeMax(MAX_FILE_SIZE); //here error The method setFileSizeMax(int) is undefined for the type ServletFileUpload
 upload.setSizeMax(MAX_REQUEST_SIZE);
 String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // here error The method getServletContext() is undefined for the type Homepage Controller
 // creates the directory if it does not exist
 File uploadDir = new File(uploadPath);
 if (!uploadDir.exists()) {
  uploadDir.mkdir();
 }

 try {
  List < FileItem > items = upload.parseRequest(request); // request is HttpServletRequest
  for (FileItem item: items) {
   if (item.isFormField()) { // text fields, etc...
    String fieldName = item.getFieldName();
    System.out.print("fieldname" + fieldName);
    value[i] = item.getString();
    System.out.print("from uploader" + value[i]);
    i++;
   } else {
    //String fileName=new File(item.getName()).getName();   Use this to use default file name
    String name = value[0];
    System.out.println("file uploader name" + name);
    String filePath = uploadPath + File.separator + name;
    System.out.println(filePath);
    File storeFile = new File(filePath);
    try {
     item.write(storeFile);
    } catch (Exception ex) {
    }
   }
  }
  System.out.println("uploaded successfully");
 } catch (Exception ex) {
  System.out.println("error not uploaded");
 }
 return new ModelAndView("ChangePhoto");
}

Three error

  1. This method must return a result of type ModelAndView
  2. The method setFileSizeMax(int) is undefined for the type ServletFileUpload
  3. The method getServletContext() is undefined for the type Homepage Controller
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
  1. Use below code to autowire ServletContext object in SpringMVC

    @Autowired
    ServletContext context; 
    

    and after that try to execute your code like

    String uploadPath = context.getRealPath("") + File.separator + UPLOAD_DIRECTORY;
    
  2. You can get it in your controller like this;

    private ServletContext context;
    
    public void setServletContext(ServletContext servletContext) {
        this.context = servletContext;
    }
    

    but for this your controller must implement ServletContextAware interface


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

2.1m questions

2.1m answers

60 comments

57.0k users

...