Upload image with HttpClient

后端 未结 2 670
庸人自扰
庸人自扰 2020-12-08 15:46

Problem

I try to upload an image with angular\'s HttpClient to API Content-Type: multipart/form-data (angular v4+). Is it supported? How to do it?

相关标签:
2条回答
  • 2020-12-08 15:53

    For me the trick was not to set the content-type to multipart/form-data. But that was done automatically for me.

    <label>
      <input type="file" (change)="setFiles($event)" style="display:none" multiple/>
      <a mat-raised-button color="primary">
        <mat-icon>file_upload</mat-icon>
        Select Documents
      </a>
    </label>
    

    Here's my code that uploads multipart/form-data. No need to set the headers.

    private setFile(event) {
        let files = event.srcElement.files
        if (!files) {
          return
        }
    
        let path = `${environment.celoApiEndpoint}/api/patientFiles`
        let data = {"patientData": {
          "uid": "",
          "firstName": "",
          "lastName": "",
          "gender": "Not Specified",
          "dateOfBirth": ""
        }}
        // let headers = new HttpHeaders()
        //   .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW')
        // let headers = new HttpHeaders().set('content-type', 'multipart/form-data')
        const formData: FormData = new FormData();
    
        for (let i = 0; i < files.length; i++) {
          formData.append(i.toString(), files[i], files[i].name);
        }
        formData.append("data", JSON.stringify(data));
        this.http.post(path, formData).subscribe(
          (r)=>{console.log('got r', r)}
        )
      }
    
    0 讨论(0)
  • 2020-12-08 16:11

    I don't think the issue is with angular, I used the same code to send a file to the server (I am using spring in backend), the only difference is I am not observing the request or converting the response to promise.

    See my code below:

    let formData: FormData = new FormData();
    formData.append('file', this.fileToUpload);
    
    this.http.put(this.usersUrl, formData).subscribe(
        data => {
            console.log(data); 
        },
        error => {
            console.log(error);
        }
    );
    
    0 讨论(0)
提交回复
热议问题