Vonage / vonage-node-code-snippets

NodeJS code examples for using Vonage
MIT License
69 stars 78 forks source link

Media Upload - Whatsapp template management API example code snippets #133

Open mithun35h opened 11 months ago

mithun35h commented 11 months ago

Can you please provide an example for the media upload https://developer.vonage.com/en/api/whatsapp-template-management#MediaUpload

Please correct me where it is going wrong

Expected Behavior

It should give a successful response

Current Behavior

Throwing error data: { type: 'https://developer.vonage.com/api-errors', title: 'Internal Server Error', instance: '1e5451e9-485d-400e-b766-cdf6ae8b266d' }

Context (Environment)

Typescript, Node v18.16.0

Steps to Reproduce


import axios from 'axios'

var FormData = require('form-data')

async function main() {
  const imageUrl = `https://fastly.picsum.photos/id/823/536/354.jpg?hmac=ysg16ZYU5mSoAtbckBDDJqI-QuuNe0YouKOIgHneSYw`

  const imageResponse = await axios.get(imageUrl, {
    responseType: 'arraybuffer',
  })

  console.log('Content-Type:', imageResponse.headers['content-type'])

  let formData = new FormData()
  formData.append('mediafile', imageResponse.data)

  const uploadMedia = await axios({
    method: 'post',
    url: `https://api.nexmo.com/v2/whatsapp-manager/media/uploads?file_type=image%2Fjpeg`,
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: `Bearer xxxx`,
    },
    data: formData,
  })

  console.log(`Upload Media: ${JSON.stringify(uploadMedia.data)}`)

}

main()
mithun35h commented 11 months ago

Can be closed i used the below code

const axios = require('axios')
const FormData = require('form-data')
const {Readable} = require('stream')

// Download the file from remote URL to a buffer
axios
  .get(
    'xxx',
    {
      responseType: 'arraybuffer',
    }
  )
  .then((response) => {
    // Convert the ArrayBuffer to a Buffer
    const buffer = Buffer.from(response.data, 'binary')

    // Convert the Buffer to a Readable Stream
    const readableStream = new Readable({
      read() {
        this.push(buffer)
        this.push(null)
      },
    })

    const formData = new FormData()
    formData.append('mediafile', readableStream, {
      filename: 'xx',
      contentType: 'xx',
    })

    return axios.post(
      'https://api.nexmo.com/v2/whatsapp-manager/media/uploads?file_type=xx',
      formData,
      {
        headers: {
          Authorization:
            'Bearer xxx',
          ...formData.getHeaders(),
        },
      }
    )
  })
  .then((response) => {
    console.log(response.data)
  })
  .catch((error) => {
    console.log(error)
  })