0

I'm trying to post an image using formdata to a nestJS powered backend and running into issues where the formdata is undefined when it reaches the backend. I tried uploading an image using postman and it worked as intended.

Here is my code for the Front end:

let blob = this.getBlob(results[i], ".png");
const file = new File([blob],name, {type:"image/png"});
let  postData = new FormData();

postData.append('file', file);

this.httpService.uploadUserPhoto(postData)
    .subscribe(res =>{
      console.log(res)
  }, error => {
 console.log(error);
this.unknownError(error.name);
})

And The Http Call

uploadUserPhoto(data: FormData){
   return this.http.post(`${this.config.serverAddress}/api/user/photoUpload`, data)
 }

The Backend uses the built in File Intreceptor to handle the image, Docs: https://docs.nestjs.com/techniques/file-upload

@Post('photoUpload')
    @UseGuards(AuthGuard)
    @UseInterceptors(FileInterceptor('file'))
    uploadFile(@User() user, @UploadedFile() file) {
        return this.profileService.saveFile(user,file)
    }

And The code for saving the uploaded image (to google cloud)

private fileUploader(userId: string, uploadedFile: any): Observable<any> {
     return new Observable(observer => {
           const fileName = `${userId}:${uniqId()}`;
           const file = this.photoBucket.file(fileName);

           const stream = file.createWriteStream({
                metadata: {
                  contentType: uploadedFile.mimetype
                 },
              resumable: false
        });

And Here is the error that the file intrecptor throws:

[Nest] 26603   - 10/28/2019, 5:38:34 PM   [ExceptionsHandler] Cannot read property 'mimetype' of undefined +106042ms
TypeError: Cannot read property 'mimetype' of undefined
    at Observable.rxjs_1.Observable.observer [as _subscribe] (PATH/dist/services/user.profile.service.js:53:47)

And Again, uploading the image file using postman works! Thanks...

4
  • Could you point out which line this is, please : services/user.profile.service.js:53:47 Commented Oct 28, 2019 at 18:06
  • @thinkwinwin Hi, ive edited the question to point to that code Commented Oct 29, 2019 at 11:08
  • uploadedFile is undefined, what are you passing to this function when calling it? Commented Oct 29, 2019 at 15:27
  • @thinkwinwin yeah, uploading the image postman works as intended Commented Oct 29, 2019 at 20:53

1 Answer 1

1

Ok, so I found out a solution for this. First of all, rather than getting a file url, get base64 from the ionic image picker. Then you create a blob from that base64 and append its content type. You can do this in any way you like but i did it via a node module, b64-to-blob (https://www.npmjs.com/package/b64-to-blob). After that, you create a form data from it and finally, http post.

Here's the code:

if (this.user.photos.length < 5) {
            this.imagePicker.getPictures({
                maximumImagesCount: 1,
                quality: 50,
                outputType: 1
            })
                .then((results: string[]) => {
                    results.forEach(res => {
                        const contentType = 'image/png';
                        // @ts-ignore
                        let blob = b64toBlob(res, contentType);
                        let fd: FormData = new FormData();
                        fd.append('file', blob);
                        this.httpUpload(fd)
                    })

                }, (err) => {
                    this.unknownError(err);
                });

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

Comments

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.