Search code examples
angularangular-forms

Angular help how to submit a file via HTTP Post


I need some assistance in trying to figure out what I'm missing trying to send a pdf/file from angular to my backend via form-data and I am having some issues doing so I am getting errors when submit is pressed via POST (error and code attached). I would appreciate any assistance!

component.ts

handleFileInput(file: File) {
this.fileToUpload = file;
}

basicUpload(files: File){
var formData = new FormData();
formData.append('file', files)

this.execSummaryUploadService.upload(formData)
 .subscribe(event => {  
})
}

HTML <div class="form-group"> <label for="file">Choose File</label> <input type="file" id="file" (change)="handleFileInput($event.target.files)"> <button mat-fab color="primary" (click)="basicUpload()">Send</button> </div>

Upload Service

constructor(private http: HttpClient) { }

public upload(formData) {
 return this.http.post<any>(this.URL, formData, {
   reportProgress: true,
   observe: 'events'
 });
}

ERROR

 core.js:15714 ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request"

Solution

  • get a single file from the event

      <input #file type="file"
             id="file"
             (change)="handleFileInput($event)">
      <button (click)="upload()">UPLOAD</button>
    
        export class AppComponent  {
    
          @ViewChild('file', { static: true }) fileInput: ElementRef;
          fileToUpload: File;
    
          constructor(private uploadService: UploadService) {
          }
    
          handleFileInput(event) {
            const fileList: FileList = event.target.files;
            console.log(fileList);
            if (fileList.length > 0) {
              const file: File = fileList[0];
              this.fileToUpload = file;
            }
          }
    
          public upload() {
            return this.uploadService.upload(this.fileToUpload)
              .pipe(
                finalize(() => {
                  this.fileInput.nativeElement.value = null;
                })
              )
              .subscribe(() => {
              });
          }
        }
    

    you can try upload service as follow

      @Injectable()
      export class UploadService {
        constructor(private http: HttpClient) {
        }
    
        upload(data: File) {
          let url = '';
    
          const content = new FormData();
          if (data !== null && data !== undefined) {
            content.append("file", data, "file");
          }
    
          let options : any = {
            body: content,
            observe: "response",
            responseType: "blob",           
            headers: new HttpHeaders({
              "Accept": "application/json"
            })
          };
    
          return this.http.request("post", url, options);
        }
      }
    

    some example but it tied to .net backend maybe not match to yours