0

So am trying to upload a file using angular 7 /ng2-file-upload , but I could not manage to do so,
because I get error 400 (field name is required) and the problem is I could not find a way to add (key name / field name) to the file.
Here is an example with Post-man:
I use Form-data and then I add a key name (imgfile) and then in the value field I browse to the file, when I click on upload it works like a charm. But if for example I changed the key name to ex: (imgs) I replicate the error that I get in angular 7.
And here is my TS :

    uploader = new FileUploader({
      url: this.FULL_URL 
    }); 
    ngOnInit() { 
    const authHeader: Array<{
        name: string;
        value: string;
    }> = [];
    authHeader.push({ 
        name: 'Authorization', 
        value: `Bearer ${this.token}`
    });

    const uploadOptions = <FileUploaderOptions>{ headers: authHeader };

    this.uploader.setOptions(uploadOptions);

    this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
        form.append('imgfile', fileItem);
     //here is where i think i should added the key name,,, but i could not 
      manage to make it work

    }; 

}  

and this is my html:

<input type="file" ng2FileSelect [uploader]="uploader">
<button (click)="uploader.uploadAll()">Upload </button>
Just Shadow
  • 10,860
  • 6
  • 57
  • 75
Jake Weary
  • 401
  • 1
  • 4
  • 17

2 Answers2

0

According to this discussion on github I think you'll need to return an object from that method.
Try this:

this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
    form.append('imgs', fileItem);
    return {fileItem, form};
}; 
Just Shadow
  • 10,860
  • 6
  • 57
  • 75
0

so, after struggling to find a solution, i finally got it, in uploader i had to add itemAlias

uploader = new FileUploader({
        url: this.FULL_URL,
        authToken: this.token`,
        itemAlias: 'imgFile'
    });
Jake Weary
  • 401
  • 1
  • 4
  • 17