2015-12-22 17 views
1

Я прочитал все вопросы, связанные с этой проблемой, но решение не работает для меня ...Spring MVC - HTTP Status 405 - Request метод «POST» не поддерживается

У меня есть простая форма загрузки. Контроллер, я контроллер, который я использовал много раз (никогда не для загрузки файлов, хотя).

@Controller 
public class FileUploadController { 
    @Autowired 
    private HttpServletRequest request; 

    @RequestMapping(value={"/upload"}, method= RequestMethod.GET) 
    public String getUploadForm() { 

     return "/upload"; 

    } 

    @RequestMapping(value={"/upload"}, method=RequestMethod.POST) 
    public @ResponseBody String uploadedFile(@RequestParam("uploadedFile") UploadedFile uploadedFile, BindingResult result, ModelMap model, 
           RedirectAttributes redirectAttributes) { 

     if (result.hasErrors()) { 
      return "/upload"; 

     } 
      InputStream is = null; 
      OutputStream os = null; 
      MultipartFile file = uploadedFile.getFile(); 
      String fileName = file.getOriginalFilename(); 
      String imagepath = request.getSession().getServletContext().getRealPath("/resources/images"); 
      try { 
       is = file.getInputStream(); 
       File newFile = new File(imagepath+"/"+fileName); 

       if(!newFile.exists()){ 
        newFile.createNewFile(); 
       } 
       os = new FileOutputStream(newFile); 
       int read=0; 
       byte[] bytes = new byte[1024]; 
       while((read = is.read(bytes)) != -1){ 
        os.write(bytes, 0, read); 
       } 
       redirectAttributes.addFlashAttribute("css", "success"); 
       redirectAttributes.addFlashAttribute("msg", "File "+fileName+ "aggiunto correttamente"); 
       model.addAttribute("fileName", fileName); 


      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     return "redirect:/floors"; 

    } 

} 

Тогда у меня есть форма загрузки, убирали форма все CSS часть:

<form:form method="POST" enctype="multipart/form-data" modelAttribute="uploadedFile"> 

     <input type="hidden" 
      name="${_csrf.parameterName}" 
      value="${_csrf.token}" /> 
     <form:errors path="*" cssClass="alert alert-danger alert-dismissible" 
      element="div" /> 


      <label class="control-label col-sm-2">Carica 
       immagine</label> 

       <input type="file" name="file"> 
       <form:errors path="file" class="control-label" /> 


     <button id="singlebutton" name="singlebutton" 
         class="btn btn-primary" type="submit">Carica</button> 

     </div> 
    </form:form> 

Я не знаю, если это полезно, но это UploadedFile.java, на самом деле просто

import org.springframework.web.multipart.MultipartFile;

public class UploadedFile{ 

    MultipartFile file; 


    public MultipartFile getFile() { 
     return file; 
    } 

    public void setFile(MultipartFile file) { 
     this.file = file; 
    } 

} 

Форма в HTML имеет:

<form id="uploadedFile" class="form-horizontal" action="/smartpark/upload" method="POST" enctype="multipart/form-data"> 

Где проблема? Я даже не могу понять, на какой запрос точка че POST идет не так ...

Я добавляю отладку: Spring отлаживать говорит:

2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 
2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 
2015-12-22 18:52:13 DEBUG HttpSessionSecurityContextRepository:192 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: '[email protected]8e6d7e: Authentication: org.spring[email protected]468e6d7e: Principal: [email protected]: Username: mario; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]7798: RemoteIpAddress: 192.168.3.38; SessionId: null; Granted Authorities: ROLE_ADMIN' 
2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter' 
2015-12-22 18:52:13 DEBUG HstsHeaderWriter:128 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.se[email protected]26ee04e5 
2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter' 
2015-12-22 18:52:13 DEBUG CsrfFilter:106 - Invalid CSRF token found for http://192.168.3.240:8080/smartpark/upload 
2015-12-22 18:52:13 DEBUG DispatcherServlet:861 - DispatcherServlet with name 'dispatcher' processing POST request for [/smartpark/Access_Denied] 
2015-12-22 18:52:13 DEBUG RequestMappingHandlerMapping:306 - Looking up handler method for path /Access_Denied 
2015-12-22 18:52:13 DEBUG ExceptionHandlerExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported 
2015-12-22 18:52:13 DEBUG ResponseStatusExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported 
2015-12-22 18:52:13 DEBUG DefaultHandlerExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported 
2015-12-22 18:52:13 WARN PageNotFound:208 - Request method 'POST' not supported 
2015-12-22 18:52:13 DEBUG DispatcherServlet:1034 - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling 
2015-12-22 18:52:13 DEBUG DispatcherServlet:1000 - Successfully completed request 
2015-12-22 18:52:13 DEBUG HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper:211 - Skip invoking on 
2015-12-22 18:52:13 DEBUG SecurityContextPersistenceFilter:105 - SecurityContextHolder now cleared, as request processing completed 

Браузер сетевых журналов ничего не говорят, только что POST ресурс не выполняется

Благодарности

+2

На боковой ноте. Вы можете использовать аннотацию requestmapping над классом '@Controller @RequestMapping (" floor ") public class' ...Таким образом, вам не нужно иметь избыточную константу по каждому методу – shinjw

+0

@shinjw хорошая точка! – fuzzy28

+0

Включите журналы отладки, проверьте, что Spring регистрирует как методы обработчика. Включите сетевые журналы вашего браузера и проверьте, что отправлено в вашем запросе. Выложите все это. –

ответ

1

вещей, чтобы рассмотреть:

Проверьте свой заголовок запроса и посмотрите, отправляет ли он floors/upload. если не пытаться добавить свойство action = "floor/upload" в свой тег формы.

Попробуйте изменить контроллер для (без path)

@RequestMapping(value="upload", method=RequestMethod.POST) 
+0

Я использовал совет от @shinjw, но я получил ту же ошибку, HTML-форму формы обращается к '

', поэтому он выглядит в правильном положении ... – besmart

+0

Вы обновили отображение запроса контроллера? – fuzzy28

+0

Да, я сделал, я обновил вопрос, чтобы отразить его советы – besmart

0

Посмотрите в PathVariables весны.

@RequestMapping(value = " /upload/{pathName}", method=RequestMethod.POST) 
public String getOrder(@PathVariable String pathName){ 
// do what you need 
} 
0

Я нашел проблему. После этого link Я видел, что многостраничную загрузку файла с помощью Spring и CSRF нужно обрабатывать с осторожностью.

Поэтому я сначала отключил CSRF, чтобы узнать, все ли хорошо. После этого, я добавил

@Override protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(servletContext, new MultipartFilter()); }

к моему SecurityWebApplicationInitializer.java так, чтобы не нужно аутентификации, чтобы загрузить файл на сервер, но только, чтобы переместить их в конечный пункт назначения.

Чем я должен был настроить filterMultipartResolver, и все прошло хорошо.

Спасибо всем

Смежные вопросы