How convert Express.Multer.File to Blob data?

Issue

I have a NestJs project in my controller I accept an Express.Multer.File but I need to send it to another server. How can I convert it to Blob for passing to FormData?

#action in my controller

    @Post('/upload')
    @UseInterceptors(FileInterceptor('avatar'))
    async uploadUserProfileAvatar(@UploadedFile() file: Express.Multer.File){
        
        console.log(file)
        let blob = new Blob(file.mimetype)
        let formData = new FormData()
        //can't set because file is not Blob
        formData.append('file',file)


        let request$ = this.httpService.post('http://test_server/file',formData,{headers:{
            'Content-Type':'multipart/form-data'
        }}).pipe(
            map(response => response.data)
        )

        request$.subscribe( response => {
            console.log(response)
            return response
        })
    }

I will be grateful for every answer!

EDIT:

Thanks again for your help! As a result, I managed to successfully send the code in this way:

    @Post('/upload')
    @UseInterceptors(FileInterceptor('avatar'))
    async uploadUserProfileAvatar(@UploadedFile() file: Express.Multer.File){

        const FormData = require('form-data');
        const formData = new FormData();
        formData.append('file', Buffer.from(file.buffer) , file.originalname);


        let request$ = this.httpService.post('http://nginx_files/file',formData,{headers:formData.getHeaders()}).pipe(
                map(response => response.data)
            )

        request$.subscribe( response => {
            console.log(response)
            return response
        })
    }

Solution

Use formdata package like this:

  const FormData = require('form-data');

  const formData = new FormData();
  formData.append('file', fileContent, 'file_name.ext');

  let request$ = this.httpService.post('http://test_server/file',
    formData,
    { headers: formData.getHeaders() }
  ).pipe(
            map(response => response.data)
        )

Answered By – Anatoly

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published