繁体   English   中英

带有多部分文件和其他参数的 Angular POST 请求

[英]Angular POST request with multipart file and other params

我想从 angular 发出 POST 请求,而后端开发人员正在等待这样的 spring 启动请求,有 3 个参数:

@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> importFile(
            @RequestParam(value = "type") Dto dto,
            @RequestParam(value = "booleanValue", required = false) Boolean booleanValue,
            @RequestParam("file") MultipartFile file)
            throws IOException {

在 Angular 方面,我正在尝试构建表单数据,但是在编写此内容时无法添加布尔值:

importFile(fileToImport: FileToImport, booleanValue?: boolean) {
    const formData = new FormData();
    formData.append('type', fileToImport.type);
    formData.append('booleanValue', booleanValue);
    formData.append('file', fileToImport.file);
    return this.http.post('/import', formData);
  }

force 出现错误: Argument of type 'boolean' is not assignable to parameter of type 'string | Blob' Argument of type 'boolean' is not assignable to parameter of type 'string | Blob'

那么我怎样才能用 3 个参数来尊重后端呢?

谢谢你的帮助

您正在尝试将布尔值传递到formData.append函数中。 您应该将其转换为字符串。

importFile(fileToImport: FileToImport, booleanValue?: boolean) {
  const formData = new FormData();
  formData.append('type', fileToImport.type);
  formData.append('force', booleanValue.toString());
  formData.append('file', fileToImport.file);
  return this.http.post('/import', formData);
}

如果您的后端特别关注如何解析布尔值,您可能需要更多的处理。 请记住,布尔值的 Javascript 字符串表示是"true""false"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM