如何通过REST服务上传文件时解决400()错误

时间:2017-10-19 06:44:38

标签: javascript java rest spring-boot file-upload

我有一个程序(Spring Boot),它使用REST服务将文件上传到服务器或任何其他给定位置。但是,当我使用相同的服务时,下面发生了错误,下面就是问题。

通过REST服务上传文件时,我收到400()错误而没有任何描述。这个应用程序是Spring启动应用程序,它使用java脚本前端通过已实现的休息服务上传和下载文件。

帮助解决此问题。感谢您的帮助。感谢。

错误是: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);

}

2 个答案:

答案 0 :(得分:2)

我在本地环境中使用这样的邮递员创建了相同的场景; 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);
}

有效。

答案 1 :(得分:0)

我的假设:您的方法saveUploadedFiles会抛出IOException。

当您收到400 Bad Request作为回复时,我认为您应该调试

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

阻止以找出导致IOException的原因。