【问题标题】:Post multipart file and json in one request with @RequestPart from angular4使用来自 angular4 的 @RequestPart 在一个请求中发布多部分文件和 json
【发布时间】:2018-05-28 22:56:02
【问题描述】:

我使用 Jhipster,这是一个控制器方法:

控制器

@RequestMapping(value = UPLOAD_URL, method = {RequestMethod.POST},
        headers = {"content-type=multipart/mixed", "content-type=multipart/form-data"},
        consumes = {"multipart/form-data"})
    public ResponseEntity<?> uploadWithMetaData(@RequestPart(value = "file") MultipartFile file,
                                                @RequestPart(value = "documentDTO") DocumentDTO documentDTO,
                                                Locale locale) throws IOException, URISyntaxException, JSONException {
  // business logic
}

基本上我想发布一个文件和一个 json 对象。

我的集成测试,我可以验证它是否按预期工作:

集成测试:

DocumentDTO documentDTO = getDocumentDTOMockFile();
Long originId = originRepository.findAll().stream().findFirst().get().getId();
documentDTO.setOriginId(originId);

MockMultipartFile jsonFile = new MockMultipartFile("documentDTO", "", "application/json",
jsonUtils.toJson(documentDTO, null).getBytes());

restClientMockMvc
      .perform(MockMvcRequestBuilders.fileUpload("/api/v1/documents/upload")
                .file(fstmp)
                .file(jsonFile))
            .andDo(MockMvcResultHandlers.log())
            .andExpect(status().isOk());

}

Angular 前端:

let fd: FormData = new FormData();
let file = fileForm.files[0];

fd.append("file", file);

let documentDTO = JSON.stringify(document);

fd.append("documentDTO",new Blob([JSON.stringify({
     "documentDTO": documentDTO})], {
         type: "application/json"
    })
);

his.httpClient.post("/api/v1/documents/upload", fd ).subscribe(request => {
   console.log("request", request);
});

我有一个拦截器,它将请求标头中的内容类型设置为:

内容类型:multipart/form-data;边界=----WebKitFormBoundary4PnIOSOLe5Djj95R

这是请求负载的样子:

这是 Spring Boot 日志消息:

已解决由 Handler 执行引起的异常:org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文件”不存在

这是我在浏览器中看到的响应:

{
  "type" : "http://www.jhipster.tech/problem/problem-with-message",
  "title" : "Bad Request",
  "status" : 400,
  "detail" : "Required request part 'file' is not present",
  "path" : "///api/v1/documents/upload",
  "message" : "error.http.400"
}

我尝试过的:

  • 将 content-type 设置为 'Content-Type' : 'multipart/mixed' => 结果相同
  • 使用 dto 和文件创建 pojo,使用 @ModelAttribute => 相同的错误
  • 然后我检查了是否有 Multipart Resolver,知道了

我没有想法,有人有什么建议吗?

【问题讨论】:

标签: java spring angular http spring-boot


【解决方案1】:

从 JavaScript 以多部分形式发布并使用如下内容:

    final WebRequest webRequest,
    @RequestParam("fileContent") final MultipartFile fileContent,
    @RequestParam("inputJson") String inputJsonString

作为参数。

如果您需要访问会话,WebRequest 很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多