2017-10-19 125 views
0

當通過REST服務上傳文件時,我得到400()錯誤,沒有任何描述。此應用程序是Spring啓動應用程序,它使用java-script前端通過實施的休息服務上傳和下載文件。400()錯誤,REST文件上傳錯誤

幫助解決這個問題。你的幫助表示讚賞。謝謝。

錯誤是:enter image description here

下面

是代碼: JS:

document.getElementById('import2').onclick = function() { 

var files = document.getElementById('selectFiles').files; 
console.log(files); 
if (files.length <= 0) { 
    return false; 
} 

//serverUploaded = true; 

var form_data = new FormData(files.item(0)); 
//from new NLP 
$.ajax({ 
    type: "POST", 
    url: "http://localhost:8080/gsta/upload", 
    processData: false, 
    contentType: false, 
    async: false, 
    cache: false, 
    data: form_data, 
    success: function (result) { 
     //alert(JSON.stringify(result)); 
     //$("#out_lexalytics").html(JSON.stringify(result)); 
     if (result) { 
      if(result.statusCode == 200) 
      { 
       serverUploaded = true; 
      } 
     } 
    } 
}); 

}

REST服務:

@PostMapping("/upload") 
// If not @RestController, uncomment this 
@ResponseBody 
public ResponseEntity<?> uploadFile(@RequestParam("data") MultipartFile uploadfile) { 

    logger.debug("Single file upload!"); 

    if (uploadfile != null && uploadfile.isEmpty()) { 
     return new ResponseEntity("please select a file!", HttpStatus.OK); 
    } 

    try { 

     saveUploadedFiles(Arrays.asList(uploadfile)); 

    } catch (IOException e) { 
     e.printStackTrace(); 
     return new ResponseEntity<>(HttpStatus.BAD_REQUEST); 
    } 

    return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK); 

} 

回答

0

我在郵局這樣的地方環境中創建了同樣的場景; (@RequestMapping(value =「/ upload」,method = RequestMethod.POST));}};

@RequestMapping(value = "/upload", method = RequestMethod.POST) 
public ResponseEntity<?> uploadFile(@RequestParam("data") MultipartFile uploadfile) { 
    logger.debug("Single file upload!"); 
    if (uploadfile != null && uploadfile.isEmpty()) { 
     return new ResponseEntity("please select a file!", HttpStatus.OK); 
    } 
    return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK); 
} 

它的工作原理。

+0

你是正確的時候使用郵遞員休息客戶端,但你有沒有嘗試AJAX調用? – DMM

+0

好的,勾選這個:[link](https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/) – Habil

0

我的假設:你的方法saveUploadedFiles拋出IOException異常。

當你得到一個400錯誤的請求作爲應答,我想你應該調試

} catch (IOException e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); }

模塊,以找出是什麼原因導致一個IOException異常。

+0

我有調試和嘗試,要求甚至沒有來的方法。 – DMM

+0

然後檢查這個答案在這裏:https://stackoverflow.com/a/21045034/4763309 – mrkernelpanic