0

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"
4
  • This is a response error from your backend server. How are you handling this request on the server? Commented May 15, 2020 at 13:19
  • I am using java spring-boot and it works in Postman when I pass in form-data with the file and API Post @RequestMapping( value = "execSummary/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE ) Commented May 15, 2020 at 13:30
  • have you tried adding a Content-Type header on the request. const headers = new HttpHeaders({'Content-Type': 'multipart/form-data'}); return this.http.post<any>(this.URL, formData, { headers, reportProgress: true, observe: 'events' });` Commented May 15, 2020 at 13:57
  • I just tried and got status: 500, error: "Internal Server Error", message: "Failed to parse multipart servlet request; nested … rejected because no multipart boundary was found", Commented May 15, 2020 at 14:24

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the help @Radik, where are you using the public upload() in the .ts file that actually calls the service?
@RobDePietro upload used as button click handler, i update my answer.
Okay that's what I thought, just wanted to make sure. Looks like everything is working and its communicating with the backend properly. I appreciate all your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.