2

I can upload files to my backend via a POST request and it returns an Http 400 Status code when the file is too big. It works perfectly when using Postman.

When I do this call in a browser (chrome), I get this error:

zone.js:2933 POST http://localhost:8080/backend/rest/upload/ net::ERR_CONNECTION_ABORTED

As a results, my HttpErrorResponse has a status code of 0:

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

This answer explains the problem, but how to I deal with this problem in Angular ? I was counting on the returned error message contained in my Http 400 response...

Tim
  • 3,910
  • 8
  • 45
  • 80
  • Just like @Miam84 said bellow this is not an Angular issue. You can check file limit. But can you give more details about your server ? I think you must handle that issue on server side ! Changing some configs I think. – Ulrich Dohou Dec 13 '17 at 16:55
  • 1
    It is only a problem when uploading files from a browser. As I wrote, using a separate rest client (Postman), I get a 400 as expected – Tim Dec 14 '17 at 08:50

1 Answers1

0

I think it's more a problem related to your API than to Angular itself... Your API should handle that and return an appropriate 400 error.

As a workaround, and to improve your UI, you can make an angular validation on the file before posting it to the backend. If it's too big, then just block the post and notify the user.

You can access the size attribute of the file like this :

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files[0].size);
  }
}
ylerjen
  • 4,109
  • 2
  • 25
  • 43
  • That's the easy solution :-) I was looking for a way to prevent the connection to be aborted. – Tim Dec 14 '17 at 08:41