Last active
December 20, 2020 11:08
-
-
Save gowthm/3cbd43cdb1d9b75519a87963586e68df to your computer and use it in GitHub Desktop.
Upload file by fs writeFile with Node Js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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