I have an upload function like this :
app.post("/upload", function (req, res) {
let base64 = req.body.image.replace(/^data:image\/png;base64,/, "");
binaryData = Buffer.from(base64, "base64").toString("binary");
fs.writeFile(
"./pictures/" + Date.now() + ".png",
binaryData,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
);
fs.writeFile(
"./thumbnails/" + Date.now() + ".png",
binaryData,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
);
The first part saves image into "pictures" folder.
That works ok, nothing to do here.
The second parts saves the same image into "thumbnails" folder.
What I need to do is to resize the image before its saved, to have only resized images in that folder.
You can try with Sharp library: https://sharp.pixelplumbing.com/api-resize
app.post("/upload", function (req, res) {
let base64 = req.body.image.replace(/^data:image\/png;base64,/, "");
binaryData = Buffer.from(base64, "base64").toString("binary");
fs.writeFile(
"./pictures/" + Date.now() + ".png",
binaryData,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
);
sharp(binaryData)
.resize({ width: 100 })
.toBuffer()
.then(data => {
// 100 pixels wide, auto-scaled height
fs.writeFile(
"./thumbnails/" + Date.now() + ".png",
data,
"binary",
function (err) {
if (err) {
console.log(err);
}
}
)
})
})
Related
I want to download a zip file using express, the point here is that by when I am trying to download txt file it is working correctly it downloads what I want. But in case of .zip format it downloads an empty file with the exact name what I want but in txt format.
static getFile(req, res) {
fileManager.getfile(req, (r) => {
if (!r.success) {
return res.status(r.code).send(r);
}
return res.download(r.result.zipFileDirName + r.result.zipFileName);
});
}
this is the get file functuion
getFile(req, callback) {
let validation = reportValidator.validateGetFile(req);
if (!validation.success) {
return callback(validation);
}
let findQuery = validation.result.query;
Something.find(findQuery).exec((err, gh) => {
if (err) {
logger.error(`Error while finding somehting, err : ${err}`);
return callback({success: false, code: 500, err: err});
}
let dirName = parentDir + req.query.accountId + '_' + req.query.dateFrom + '_' + req.query.dateTo + '/';
let archive = archiver('zip', {
gzip: true,
zlib: { level: 9 }
});
archive.on('error', (err) => {
logger.error(err);
return callback({success: false, code: 500, err: err});
});
archive.on('end', () => {
console.log('Archive wrote %d bytes', archive.pointer());
});
let zipFileName = req.query.accountId + '_' + req.query.dateFrom + '_' + req.query.dateTo + '.zip';
let zipFile = fs.createWriteStream(dirName + zipFileName);
archive.pipe(zipFile);
async.each(gh,
(item, next) => {
let fileName = item.handId + '_' + Date.now() + '.mat';
this.makeReportingFile(dirName, fileName, item.gameInfo, r => {
if (!r.success) {
return next(err);
}
archive.file(r.result.file, {name: item.handId + '.mat'});
next(null, 'OK');
});
},
(err) => {
if (err) {
logger.error(JSON.stringify(err));
return callback({success: false, code: 500, err: err});
}
archive.finalize();this on end
return callback({success: true, code: 200, result: {message: "OK", zipFileDirName: dirName, zipFileName: zipFileName}});
});
});
}
I have provided additional info
I need to convert & write each base64 string from an array to a different file by using fs.writeFile but only the last array element is saved. Have a look at my code below :
let receivedData =["iVBORw0KGgoAAAANSUhEUgAABM...", "4AAANiCAYAAACZ8IVOAAAKqGlDQ1BJQ0MgU..."]:
//decode base 64 to buffer
let decodeBase64 = (dataArray) => {
let result = [];
dataArray.forEach((element) => {
result.push(Buffer.from(element, 'base64'));
})
return result; //array
};
let writeFileAsync = (data) => {
let filename = Date.now() + '.jpeg';
return new Promise((resolve, reject) => {
data.forEach((value) => {
fs.writeFile(filename, value, (err) => {
if(err){
reject(err);
} else {
console.log('file is saved');
resolve(value);
}
})
})
}
let decoded = decodeBase64(receivedData);
writeFileAsync(decoded)
.then((result) => {
console.log('file is saved');
})
.catch((error) => {
console.log(error);
})
the last value of receivedData is saved to filesystem but not the first element
I know it has something to do with doing async method in a loop and maybe something else. The loop just imcrement before writefile finishes.
Any helps/tips would be appreciated thx
Try this, It will upload your file one by one, it will take time but git you the appropriate result:
let fileUpload = async (FILES , PATH, CB)=>{
/** image Path **/
let lengthOfFiles = FILES.length, RETURN_IMAGEPATHS = [], count = 0,
uploadFunc= [];
for(let index= 0; index < lengthOfFiles; index++){
let name = Date.now() + ".png";
RETURN_IMAGEPATHS.push('http://localhost:3000/' + <PATH_FOR_FILE> + name);
uploadImage(<Image save path>, <Imagte file path>, FILES[index]);
}
CB(null, RETURN_IMAGEPATHS);
};
function uploadImage(imageSavePath, filePath, FILE){
return new Promise(async (resolve, reject)=> {
await fs.writeFileSync(imageSavePath, FILE, "base64", function (err) {
if (err)
reject(err);
else {
filePath ='http://localhost:3000/' + filePath;
resolve(filePath);
}
});
})
}
fileUpload(FILES , PATH, (err)=>{
if(err){
console.log(err);
}
else
console.log('Success');
})
problem with file name in Multer
i am using express.js and multer to upload images to server. i act like this:
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "../client/member/upload");
},
filename: function (req, file, callback) {
console.log('1', 1);
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage : storage}).single('userPhoto');
but the problem is that never file name changes.
my uploader handler:
function memberUpload(request, response) {
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "../client/member/upload");
},
filename: function (req, file, callback) {
console.log('1', 1);
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage : storage}).single('userPhoto');
var folderName = path.join(__dirname, '../', 'client/member/upload');
if (!fs.existsSync(folderName)) {
fs.mkdir(folderName, function (err) {
if (err) {
return response.status(500).send(err);
}
else {
upload(request, response, function (err) {
if (err) {
return response.status(400)
.send('No files were uploaded.');
}
var sentFile = request.files.file,
fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';
sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName)); // => 'text/plain'
if (err) {
return response.status(500)
.send(err);
}
response.send({'location': '../member/upload/' + fileName});
});
});
}
});
}
else {
upload(request, response, function (err) {
if (err) {
return response.status(400)
.send('No files were uploaded.');
}
var sentFile = request.files.file,
fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';
sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName)); // => 'text/plain'
if (err) {
return response.status(500)
.send(err);
}
response.send({'location': '../member/upload/' + fileName});
});
});
}
}
the file save into correct directory with name "blobid0.jpeg", "blobid1.png" and so on ...
what is my fault?
Here is my code for uploading any file(pdf, txt, png) to server.Hope this will help you.
exports.saveMedia = ((req, res) => {
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, (config.const.path.base + config.const.path.productReviewMedia));
},
filename: (req, file, callback) => {
callback(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({storage: storage}).any('file');
upload(req, res, (err) => {
if (err) {
return res.status(400).send({
message: helper.getErrorMessage(err)
});
}
let results = req.files.map((file) => {
return {
mediaName: file.filename,
origMediaName: file.originalname,
mediaSource: 'http://' + req.headers.host + config.const.path.productReviewMedia + file.filename
}
});
res.status(200).json(results);
});
});
I'm resizing an image using gm library but it create an empty image. I use different ways for writing result but everytime get empty image.
gm(readStream)
.size({bufferStream: true}, function(err, size) {
this.resize(100, 100, '%')
.stream()
.on('end',function(){
console.log('done');
})
.on('error',function(err){
console.log(err);
})
.pipe(writeStream);
});
I also use this way but result was the same.
gm(srcPath)
.resize(100, 100)
.stream(function(err, stdout, stderr) {
if(err){
console.log('ERRoor:', err);
}
// ws = fs.createWriteStream( output );
i = [];
stdout.on( 'data', function(data){
// console.log('data');
i.push( data );
});
stdout.on( 'close', function(){
console.log( 'close' );
var image = Buffer.concat( i );
writeStream.write( image.toString('base64'), 'base64' );
writeStream.end();
});
});
And this way too:
gm(srcPath)
.resize(100, 100)
.write(writeStream, function (err) {
var thumbUrl, error;
if (err) {
error = err;
} else{
thumbUrl = thumbPath.replace(/\\/g, '/');
thumbUrl = thumbUrl.replace(/^\.\/public/, '');
}
callback(error, thumbUrl);
});
this way every time return en empty object({}) as error!
<!--This code is used to generate a bar code, create an image file and then make the file available for download in the browser-->
bwipjs.loadFont('Inconsolata', 108, require('fs').readFileSync('node_modules/bwip-js/fonts/Inconsolata.otf', 'binary'));
bwipjs.toBuffer({
bcid: 'code128',
text: 'ID:' + result[0]._id + '\nDevice Name:' + result[0].device_name + '\nDevice Model' + result[0].device_model,
scaleX: 0.5,
scaleY: 0.5
}, function(err, png) {
if (err) {
console.log("Error in generating barcode");
console.log(err.stack);
}
fs.writeFile('images/' + device + '.png', png, function(err) {
if (err) {
return console.error(err);
}
});
res.download('images/' + device + '.png', device + 'png', function(err) {
if (err) {
console.log("Error:");
return console.error(err);
}
});
});
writeFile is async. You need to move download part into callback
bwipjs.loadFont('Inconsolata', 108, require('fs').readFileSync('node_modules/bwip-js/fonts/Inconsolata.otf', 'binary'));
bwipjs.toBuffer({
...
function(err, png) {
if (err) {
console.log("Error in generating barcode");
console.log(err.stack);
}
fs.writeFile('images/' + device + '.png', png, function(err) {
if (err) {
return console.error(err);
}
else { // run when file was written to disk
res.download('images/' + device + '.png', device + 'png', function(err) {
if (err) {
console.log("Error:");
return console.error(err);
}
});
}
});
});