没有文件到后端的角度上传文件(400错误请求)

问题描述 投票:1回答:1

如何上传没有文件的文件到后端

我在参数中向文件发送空值(不选择文件)

角度:

//this.currentFileUpload -> null
this._reportService.createReportTemplate(this.reportTemplate.code, this.reportTemplate.name, this.reportTemplate.status, this.currentFileUpload)
        .subscribe(res => {

            console.log('Save report', res);
        });

Angular服务:

private httpOptions(): HttpHeaders {
    return new HttpHeaders({
        'Authorization': token is here // doesn't matter
    });
};


createReportTemplate(templateCode: string, templateName: string, status: string, file: File): Observable<any> {
    const data: FormData = new FormData();

    data.set('file', file);
    return this
        .http
        .post('/address/upload' + templateCode + '&Rname=' + templateName + '&Status=' + status, data, {headers: this.httpOptions()});
}

后端:

@PostMapping(value="/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation(value = "With upload file")
public CReportTemplates create(@RequestParam("file") MultipartFile file,
                               @RequestParam("Code") String code,
                               @RequestParam("Rname") String rname,
                               @RequestParam("Status") String status
) throws IOException {}
java angular spring typescript
1个回答
1
投票

您需要在Spring声明中将期望为null的参数设置为可选

角度

我建议检查文件是否存在或已被选择,因此您不要发送到后端。

const data: FormData = new FormData();
if ( file != null /* or whatever clause you want to test that the file exists or not */ ) {
  data.set('file', file);
}

春季后端

表示参数是可选的。根据您的Spring和Java版本,实现可能有所不同。

// In case of Java < 8, try this
@RequestParam(value = "file", required = false) MultipartFile file,

// In case of Java > 8, try this
@RequestParam("file") Optional<MultipartFile> file,

© www.soinside.com 2019 - 2024. All rights reserved.