使用Angular2将MultipartFile作为请求参数发送到REST服务器

时间:2017-05-23 08:15:48

标签: spring angular http spring-boot

我需要将照片上传到使用Spring Boot编写的服务器。对于发送请求的前端,我使用Angular2。

这是我接受HTTP请求的API。它工作正常。 (我用Postman测试过它)

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo")
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){

    if (file.isEmpty()) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage("DEBUG: Attached file is empty");
        return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
    }
    String returnPath = null;
    try {
        // upload stuff
    } catch (IOException e) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(e.getMessage());
        return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<String>(returnPath, HttpStatus.OK);
}

我不确定如何在Angular2中编写代码来调用服务器。 以下就是我的想法。

 savePhoto(photoToSave: File) {

    let formData: FormData = new FormData();
    formData.append('file', photoToSave);

    let savedPath = this._http
        .post(this._endpointUrl + "tender/save-new/save-photo", formData)
        .map(
        res => {
            return res.json();
        }
        )
        .catch(handleError);

    return savedPath;
}

如您所见,我在发送表单数据之前将'file'参数附加到表单数据中。服务器方法接受RequestParam'file'

但是,在服务器日志中,我收到以下错误。

  

org.springframework.web.multipart.MultipartException:当前请求   不是多部分请求   org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190)

请注意,我没有声明CommonsMultipartResolver bean,因为SprinBoot会隐式处理它。 (我听说过。如果我错了,请纠正。)

我认为由于请求中缺少值而导致错误。春天handleMissingValue说的是什么?我错过了什么?

2 个答案:

答案 0 :(得分:1)

您需要指定您的控制器需要多部分

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo", consumes = {"multipart/form-data"})
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){

另外要解决CORS问题,你需要添加你计划在你的cors映射中使用的方法,试试这样的事情

 @Configuration
 public class WebMvcConfiguration {

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
        }
    };
}
}

答案 1 :(得分:0)

我有同样的问题,这是我现在正在使用的解决方案:

使用弹簧靴的后端:

current_balance
使用Angular2的前端

try 
     % put your ode15s process here
catch
     % put statement to handle errors like 
     fprintf('Error found.')
     % or skip the error one, then run the next process
end