简体   繁体   中英

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". 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". So how can i implement a valid "post" for multipart/form-data with angular 6?

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:

<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. 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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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