FormData文件上传以及其他FormData参数

时间:2019-01-29 10:26:43

标签: angular typescript multipartform-data

我也在尝试上传文件以及一些表单数据。昂首阔步的curl命令如下所示,并且顺利通过。

curl -X POST "https://<server>/credentials/k8s" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "kubeConfig=@k8s-config-file;type=" -F "name=aaaa"

但是当我尝试使用angular进行相同的操作时,我仅获得name参数,而没有获取kubeConfig文件。我的代码如下:

HTML:

<form #kubernetesCredentialForm="ngForm" (ngSubmit)="addKubernetesCredential(kubernetesCredentialForm.value);"
    ngNativeValidate>
    <section class="form-block">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" placeholder="Name" name="name" ngModel required>
        </div>
        <div class="form-group">
            <label for="kubeConfig">Kube Config File</label>
            <input type="file" placeholder="Kube Config File" name="kubeConfig" ngModel>
        </div>
    </section>
    <button type="submit" class="btn btn-primary">ADD</button>
</form>

组件:

public addKubernetesCredential(credential) {
    this.endpointService.addk8sCredential(credential).subscribe(
        res => {
            this.alertMessage = 'Credentials added successfully!';
        }, err => {
            this.alertMessage = 'Credentials was not added.';
        });
}

服务:

public addk8sCredential(credential) {
    let body = new FormData();
    body.append("name", credential.name);
    body.append("kubeConfig", credential.kubeConfig, "k8s-config-file");
    return this.http.post('/credentials/k8s', body);
}

我的后端服务:

@PostMapping(value = "/credentials/k8s", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String addCredentials(@RequestParam(name = "kubeConfig", required = false) MultipartFile kubeConfig, @RequestParam("name") String name){

    }

我仅从表单数据而不是name文件中获取kubeConfig参数。我在哪里犯错?预先感谢!

0 个答案:

没有答案