2016-06-28 2 views
1

Я пытаюсь загрузить файлы через Angular 1.5 в конечную точку REST Spring.Spring REST не получает файлы из MultiPartHttpServletRequest

У меня нет ошибок, потому что multiPartRequest.getFileNames(); возвращает null. Однако мой JS POST, похоже, правильно проходит запрос.

Однако я не могу работать. Я смотрел на него часами и нуждался в том, чтобы кто-то указал на очевидную вещь, которую я пропустил.

Любая помощь, предложения приветствуются.

POST Пример запроса:

Accept:application/json, text/plain, */* 
Accept-Encoding:gzip, deflate 
Accept-Language:en-US,en;q=0.8 
Connection:keep-alive 
Content-Length:50188 
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryIPlVKLnf1ZIQNPHV 
Host:localhost:8080 
Origin:http://127.0.0.1:49693 
Referer:http://127.0.0.1:49693/test.html 
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 
Request Payload 
------WebKitFormBoundaryIPlVKLnf1ZIQNPHV 
Content-Disposition: form-data; name="file"; filename="post-image1.jpg" 
Content-Type: image/jpeg 


------WebKitFormBoundaryIPlVKLnf1ZIQNPHV-- 
Name 

Я использую ниже HTML

   <form enctype="multipart/form-data">      
         <input type="file" name="file" onchange="angular.element(this).scope().upload(this.files)"/> 
         <button type="submit">Upload</button> 
         <li ng-repeat="file in files">{{file.name}}</li> 
       </form> 

С follwing JS

$scope.upload = function(files) { 
      var fd = new FormData(); 
      //Take the first selected file 
      fd.append("file", files[0]); 

      $http.post('uploadURL', fd, { 
       withCredentials: true, 
       headers: {'Content-Type': undefined }, 
       transformRequest: angular.identity 
      }) 
      .success(function(d) { 
        console.log("Upload complete" +d); 
      }) 

     }; 

И на следующей REST конечной точки

@RequestMapping(value="/upload", method=RequestMethod.POST) 
    public String upload (HttpServletResponse response, HttpServletRequest request) { 

     MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest) request; 

     Iterator<String> it = multiPartRequest.getFileNames(); 
     while (it.hasNext()) { 
      MultipartFile multiPartFile = multiPartRequest.getFile(it.next()); 

      String filename = multiPartFile.getOriginalFilename(); 
      imageName = filename; 

      String path = new File("src/main/resources/images").getAbsolutePath() + "/" + filename; 

      try { 
       multiPartFile.transferTo(new File(path)); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     return null; 
    } 
+0

Путь не доступен, изменить путь, как 'C: \\ images' , –

+0

@RomanC не доходит до того, что итератор пуст, потому что multPartRequest.getFiles возвращает пустой список. – Yonkee

+0

Действительно, файлы не загружаются. –

ответ

1

Попробуйте сделать так

@RequestMapping(value="/upload", method=RequestMethod.POST) 
public String upload(MultipartHttpServletRequest request, 
     HttpServletResponse response) { 
(...) 
+0

Спасибо за предложение. Это действительно работает? – Yonkee

+0

@Yonkee Да, он работает и должен работать. –

0

У меня такая же проблема, я решить ее изменения <button type="submit">Upload</button> в <input type="submit">