【发布时间】:2018-12-31 00:16:31
【问题描述】:
我正在尝试为 angular 6 的 excel 文件创建上传表单。我已经实现了一个文件选择器,我想使用该文件选择器将 excel 文件上传(发布)到某个需要“MULTIPART_FORM_DATA”的端点。现在我已经读到您不应该在标题中为 5 以上的 Angular 版本设置内容类型,但如果我不在标题中包含内容类型,则 Angular 应用程序会自动将其设置为 “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,这是服务器不期望的,因此会导致“错误请求”。那么我怎样才能为 angular 6 的 multipart/form-data 实现一个有效的“post”呢?
端点看起来像这样:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadExcel(
@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader){...}
角度组件看起来像这样:
handleFileInput(event: any): void {
if (!event.target.files.length) {
return;
}
this.fileToUpload = event.target.files.item(0);}
private uploadFile(): void {
this.fileService.uploadFile(this.fileToUpload).subscribe(
(res: any) => {
console.log('upload succeeded');
}
);}
html 表单看起来像这样:
<form (submit)="uploadFile()" enctype="multipart/form-data">
<label for="file">choose excel file to upload: </label>
<input type="file" name="file" id="file" accept=".xls,.xlsx" (change)="handleFileInput($event)">
<input type="submit" name="submit" class="submitButton">
服务看起来像这样:
uploadFile(file: File): Observable<any> {
const fd: FormData = new FormData();
fd.append('file', file, file.name);
return this.http.post(this.fileURL, file);
}
【问题讨论】:
标签: excel angular post multipartform-data angular6