2017-10-19 10 views
0

RESTサービス経由でファイルをアップロードする際に、何も説明せずに400()エラーが発生します。このアプリケーションは、Javaスクリプトのフロントエンドを使用して実装されたレストサービスを介してファイルをアップロードおよびダウンロードするSpringブートアプリケーションです。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

このような郵便受けを使用して私のローカル環境で同じシナリオを作成しました。 enter image description here

小さな変更(@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不正な要求を取得しているように、私はあなたのIOExceptionの原因を見つけるためにあなたの

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

ブロックをデバッグするべきだと思います。

+0

私はデバッグして試してみましたが、要求はメソッドにも来ていません。 – DMM

+0

次に、この回答を確認してください:https://stackoverflow.com/a/21045034/4763309 – mrkernelpanic

関連する問題