2017-10-19 217 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