0

I'm creating small program that allows you to save images. And it saves the images on the system. This is the code:

app.post('/upload',async (req,res)=>{
  imageData = req.body.imageData
  imageData = imageData.replace(/^data:image\/png;base64,/, "")
  imageData = imageData.replace('+','')
  imageData = new Buffer(imageData, 'base64').toString('binary')
  extension = req.body.extension
  dev = req.body.dev
  console.log(req.body)
  if(extension != 'png' && extension != 'jpg' && extension != 'svg' && extension != 'jpeg' && extenstion != 'gif'){
    res.json({
      ok: false, 
      message: `Extension isn't supported`
    })
    return
  }
  id = nanoid(20)
  fs.writeFileSync(`static-cache-images/${id}.${extension}`,imageData)
  if(dev){
    await db.collection('dev-images').insertOne({id: id, fileBuffer: imageData, extension: extension})
  }else{
    await db.collection('images').insertOne({id: id, fileBuffer: imageData, extension: extension})
  }
  res.json({
    ok: true, 
    id: id,
    extension: extension
  })
})

Then from another server I'm sending a post request trying to save the image to this server:

const request = require('request')
const fs = require('fs')

request.post({
  uri: `server_url/upload`,
  json: {imageData: fs.readFileSync(`hackermon.png`).toString('base64'), extension: 'png', dev: true}
},(err,res,body)=>{
  if(err){
    throw err
  }
  console.log(body)
})

but it doesn't work. on my first server there is a file but it doesn't recognize as image.

Hackermon
  • 78
  • 1
  • 7

0 Answers0