2014-11-14 12 views
31

Ho bisogno di caricare immagini nel mio progetto. Come ottenere il percorso di caricamento in SpringMVC. Il percorso è;come ottenere getServletContext() in primavera controller mvc

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

Il seguente errore;

The method getServletContext() is undefined for the type HomePageController 

appare quando utilizzo questo codice;

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

mio codice è

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"); 
} 

Tre errore

  1. Questo metodo deve restituire un risultato di tipo ModelAndView
  2. Il metodo setFileSizeMax (int) è definito per il tipo ServletFileUpload
  3. Il metodo getServletContext() non è definito per il tipo Homepage Contro ller

risposta

52
  1. Usa sotto il codice per autowire ServletContext oggetto in SpringMVC

    @Autowired 
    ServletContext context; 
    

    e dopo che cercano di eseguire il codice come

    String uploadPath = context.getRealPath("") + File.separator + UPLOAD_DIRECTORY; 
    
  2. Puoi farlo nel tuo controller in questo modo;

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

    ma proprio per questo il controller deve implementare l'interfaccia ServletContextAware

13

Prova questo:

@Autowired 
ServletContext servletContext; 
8

Questa è solo un'altra alternativa

((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext() 
Problemi correlati