send image with formdata in angular not working

Viewed 10

I am trying to send an image file to be server with formdata, but I don't have the expected payload

the be expects a form data like this: { attachedFile: file }. But my code sends a payload like this

enter image description here

How can I send the image correctly?

const input = document.createElement('input');
input.setAttribute('type', 'file');
input.click();

input.onchange = () => {
  let file: any;
  if (!input.files) return; 
  file = input.files[0];
  if (/^image\//.test(file.type)) {
    const reader = new FileReader();
    reader.onload = () => {
      this.quillEditorRef.focus();
      const range = this.quillEditorRef.getSelection();
      let imgPath = this.uploadFile(file);
  }

  private uploadFile(file: File) {
    let imgPath: string = '';
    this.httpDashboard.uploadFile(file).subscribe((response: UploadFileDto) => {imgPath = response.imgURL});
    return imgPath;
  }

   public uploadFile(file: any): Observable<UploadFileDto> {
        const formData = new FormData();
        formData.append("attachedFile", file);

        let headers = new HttpHeaders();
        headers.append('Content-Type', 'multipart/form-data');

        return this.http.post(`/api/messages/upload-file`, formData, {headers: headers}) as Observable<any>;
    }
0 Answers
Related