0

I am trying to upload image on server as I am getting base64 string when user is uploading image from an android app though I am getting that base64 string on backend but how can I convert it into image and save it into some directory.

Below is my code:

server.js

const express = require('express');
const app = express();

const port = process.env.PORT || 3000;

app.use(require('./routes/upload'));

app.listen(port, console.log(`App is running at ${port} port.`));

upload.js

const express = require('express');
const router = express.Router();

router.use(express.json());
router.use(express.urlencoded({extended:true}));

router.post('/upload',(req,res) => {

   const name = req.body.base64Image;
   console.log(name);
});

module.exports = router;

Someone let me know how can I achieve desired result.

3 Answers 3

2

You can use fs to save base64 line to image file

fs.writeFileSync(path.join(uploadPath, fileName), new Buffer(base64, 'base64'))
Sign up to request clarification or add additional context in comments.

1 Comment

For TypeScript developers, new Buffer has been deprecated. Buffer.from should be used instead
2

You need to create a buffer

const base64Data = new Buffer.from(req.body.base64data.replace(/^data:image\/\w+;base64,/, ""), 'base64');

Then should be able to save or upload to s3 etc

2 Comments

I want to save this image in upload directory so how can I give it a path to upload.
If you want that, you can use multer
0

For those looking for a solution in Node:

function dataURLtoFile(dataUrl: string, filename: string): File {
    const [header, base64Data] = dataUrl.split(",");
    const mimeType = header.match(/:(.*?);/)?.[1] || "image/png";

    const buffer = Buffer.from(base64Data, "base64");

    return new File([buffer], filename, { type: mimeType });
  }

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.