2015-04-07 11 views
5

TŁOjQuery Ajax upload plików: Wymagane MultipartFile parametr „plik” nie jest obecny

Buduję Wiosna aplikację internetową MVC na Java8 i uruchomienie go na tomcat8. Oprócz tych informacji, wersja Spring to 4.1.6.RELEASE i Servlet 3.1 Daję ci tło środowiskowe, ponieważ niektóre rozwiązujące problemy wspomniane wersja jest związana z tym błędem.

mój kod

Poniżej root-context.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   
    <property name="maxUploadSize" value="20000000" /> 
</bean> 

Poniżej jest moje FileController

@Controller 
public class FileController { 
    private static final Logger logger = LoggerFactory.getLogger(FileController.class); 

    private static final String UploadFolder = "Files"; 

    @RequestMapping("/uploadFile") 
    @ResponseBody 
    public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {  
     String fileName = ""; 
     PrintWriter script = response.getWriter(); 

     if (!file.isEmpty()) { 
      try { 
       byte[] bytes = file.getBytes(); 

       fileName = FilenameUtils.getName(file.getOriginalFilename()); 

       String extension = FilenameUtils.getExtension(fileName); 



       String base = System.getProperty("catalina.home"); 

       File dir = new File(base + File.separator + UploadFolder);     

       if (!dir.exists()) { 
        dir.mkdirs(); 
       } 

       Date date = new Date(); 
       String year = DateTimeUtility.getInstance().getYear(date); 
       String month = DateTimeUtility.getInstance().getMonth(date); 
       String uniqueFileName = DateTimeUtility.getInstance().getDateTime(date); 

       File dateDir = new File(base + File.separator + UploadFolder + File.separator + year + File.separator + month); 

       if (!dateDir.exists()) { 
        dateDir.mkdirs(); 
       } 

       File uploadedFile = new File(dateDir.getAbsolutePath() + File.separator + uniqueFileName + WordCollections.UNDERBAR + fileName); 

       BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(uploadedFile)); 

       stream.write(bytes); 
       stream.close(); 

       logger.info("Server File Location = " + uploadedFile.getAbsolutePath());     
       script.write("Uploading file was successful"); 
      } catch (Exception e) {    
       logger.error("Server failed to upload this file : " + fileName); 
       script.write("Uploading file was failed"); 
      } 
     } else { 
      logger.error("The requested file is empty"); 
      script.write("Uploading file was empty"); 
     } 
    } 

Poniżej jest moja forma

<form id="upload" method="POST" action="/uploadFile.json" enctype="multipart/form-data"> 
     File to upload: <input type="file" name="file" onchange="MyScript.uploadFile(this);"><br /> 
     <input type="submit" value="Upload"> Press here to upload the file! 
    </form> 

Najdziwniejsze

jest to, że przesyłanie plików za pośrednictwem form submit nie ma problemu. To działa jak urok !! Nie mam nic do narzekań na form submit !!

ale to AJAX PONIŻEJ NIE DZIAŁA

  $.ajax({ 
       type: "POST", 
       url: "/uploadFile", 
       data: {name: "file", file: inputElement.files[0]}, 
       contentType: 'multipart/form-data;boundary=----WebKitFormBoundary0XBBar2mAFEE8zbv', 
       processData: false, 
       cache: false, 
       /*beforeSend: function(xhr, settings) { 
        xhr.setRequestHeader("Content-Type", "multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p"); 
        settings.data = {name: "file", file: inputElement.files[0]};      
       },*/ 
       success: function (result) {       
        if (result.reseponseInfo == "SUCCESS") { 

        } else { 

        } 
       }, 
       error: function (result) { 
        console.log(result.responseText); 
       } 
      }); 

Kiedy próbuję przesłać plik z powyższego wywołania ajax, serwer wyrzuca mi ten błąd.

2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing POST request for [/uploadFile] 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /uploadFile 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException] 
2015-04-07 18:37:30 DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'fileController' 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling 
2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request 

A przeglądarka mówi coś takiego ...

<body><h1>HTTP Status 400 - Required MultipartFile parameter 'file' is not present</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>Required MultipartFile parameter 'file' is not present</u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect.</u></p><hr class="line"><h3>Apache Tomcat/8.0.20</h3></body></html> 

Chodzi Wymagane MultipartFile parametr 'plik' nie jest obecny i 400 Bad Request.

Mam google z tego słowa kluczowego i przeszukiwane jak mogłem, jak zawsze przed wysłaniem pytanie na stackoverflow

ja naprawdę nie rozumiem dlaczego tylko ajax nie działa tutaj !! po przesłaniu upload działa dobrze.

+0

Używasz action = "/ uploadFile.json". Czy ten plik jest już dostępny? –

+0

Upewnij się, że 'inputElement.files [0]' nie jest pusty. – Turtle

+0

@Turtle Na pewno nie jest zerowy. – hina10531

Odpowiedz

5

Daj spróbować tak:

var fd = new FormData(); 
fd.append("file", $("input[name=file]").files[0]); 

$.ajax({ 
       type: "POST", 
       url: "/uploadFile", 
       data: fd, 
       contentType: false, 
       processData: false, 
       cache: false, 
       /*beforeSend: function(xhr, settings) { 
        xhr.setRequestHeader("Content-Type", "multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p"); 
        settings.data = {name: "file", file: inputElement.files[0]};      
       },*/ 
       success: function (result) {       
        if (result.reseponseInfo == "SUCCESS") { 

        } else { 

        } 
       }, 
       error: function (result) { 
        console.log(result.responseText); 
       } 
      }); 
+0

Hej! Działa jak urok ~! ustawienie 'contentType: false' na ajax i umieszczenie moich danych pliku w obiekcie' FormData' rozwiązało mój problem ~! Nigdy nie myślałem o użyciu "FormData". Czy możesz wyjaśnić, dlaczego działa ajax? i dlaczego mój oryginalny kod nie jest wcześniej? – hina10531

+0

Lepiej nie ustawiać typu zawartości ręcznie w żądaniu ajax, aby wysłać żądanie danych wieloczęściowych, ponieważ w nagłówku żądania nie będzie brakowało łańcucha ograniczającego, a serwer wie, gdzie zaczyna się wartość parametru i kończy się w przypadku żądania danych wieloczęściowych. –

+0

To nie zadziałało dla mnie, ale to zrobiło 'fd.append (" file ", $ ('input [type = file]') [0] .files [0])' –

Powiązane problemy