Skip to content

Instantly share code, notes, and snippets.

@gowthm
Last active December 20, 2020 11:08
Show Gist options
  • Save gowthm/3cbd43cdb1d9b75519a87963586e68df to your computer and use it in GitHub Desktop.
Save gowthm/3cbd43cdb1d9b75519a87963586e68df to your computer and use it in GitHub Desktop.
Upload file by fs writeFile with Node Js
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.post('/upload-file', async function(req, res) {
const fileName = req.body.fileName;
const base64 = req.body.base64Data;
console.log(base64);
const file = fileName + '.'+'png';
const bufferBase64 = Buffer.from(base64.replace(/^data:([A-Za-z-+\/]+);base64,/, ''), 'base64');
const filePath = path.join(process.cwd() + '/uploads/' + file);
console.log(filePath);
return new Promise((resolve, reject) => {
fs.writeFile(filePath, bufferBase64, 'base64', (err) => {
if(err) {
reject(err)
} else {
resolve('uploaded successfully');
}
})
})
})
app.listen(3000, () => console.log('started server'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment