Monday, January 16, 2023

Save file in node js filesystem then upload to server

Save to local filesystem : 

 const fs = require('fs')

// Read the image file as a buffer

const imageBuffer = fs.readFileSync('path/to/image.jpg')

// Encode the image buffer as a base64 string

const imageBase64 = imageBuffer.toString('base64')

// Save the base64 encoded image to a local file

fs.writeFileSync('path/to/local/image.txt', imageBase64)


Upload to server from local filesystem:

const axios = require('axios')

const FormData = require('form-data')


// Read the local image file as a buffer

const imageBuffer = fs.readFileSync('path/to/local/image.txt')


// Decode the base64 encoded image to a buffer

const image = new Buffer.from(imageBuffer.toString(), 'base64')


const formData = new FormData()

formData.append('image', image)

const options = {

  headers: {

    'Content-Type': 'multipart/form-data'

  }

}

axios.post('api_endpoint_url', formData, options)

  .then((response) => {

    console.log(response.data)

  })

  .catch((error) => {

    console.log(error)

  })