[英]Post multipart/form-data to endpoint
I'm trying to create an upload form for excel files with angular 6. I have implemented a file chooser with which i want to upload (post) excel files to a certain endpoint that expects "MULTIPART_FORM_DATA". 我正在尝试为角度为6的excel文件创建一个上传表单。我实现了一个文件选择器,我想使用该文件选择器将excel文件上传(发布)到某个期望“ MULTIPART_FORM_DATA”的端点。 Now i have read that you should not set the content type in the header for angular versions above 5 but if i do not include the content-type in the header the angular application automatically sets it to "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", which the server does not expect and hence results in a "bad request".
现在,我了解到您不应该在头版本中为高于5的角版本设置内容类型,但是如果我在头中不包含内容类型,则角应用程序会自动将其设置为“ application / vnd.openxmlformats-officedocument.spreadsheetml “ .sheet”,服务器不会期望它,因此会导致“错误请求”。 So how can i implement a valid "post" for multipart/form-data with angular 6?
那么,如何为角度为6的multipart / form-data实现有效的“ post”?
the endpoint looks something like this: 端点看起来像这样:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadExcel(
@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader){...}
the angular component looks something like this: 角度分量看起来像这样:
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');
}
);}
the html form looks something like this: 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">
and the service looks like this: 服务看起来像这样:
uploadFile(file: File): Observable<any> {
const fd: FormData = new FormData();
fd.append('file', file, file.name);
return this.http.post(this.fileURL, file);
} }
I found the mistake I've made: I passed the wrong argument to the http.post call. 我发现了自己犯的错误:我将错误的参数传递给http.post调用。 The service should of course look like this:
该服务当然应如下所示:
uploadFile(file: File): Observable<any> {
const fd: FormData = new FormData();
fd.append('file', file, file.name);
return this.http.post(this.fileURL, fd);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.