I am using Ionic v3 and and for backend used Nodejs.
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
});
var upload = multer({storage: storage});
To call this method we require req ,res through API call like below,
upload(req, res, function(err) {
res.end('File is uploaded')
});
My question that is it possible to call this upload function without API call(req,res) ? If yes how can we do ?
What i want to do is, I am developing chat application using ionic2 and nodejs where i can share image. That image should be upload to server side. How can I do for socket programming ?
If you want to upload image using base64 then you can use following code
socket.on('Upload_Image_base64', function(data)
{
var fs = require('fs');
var img = data.image64;
var imgname = new Date().getTime().toString();
imgname = data.userid + imgname + '.png';
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(__dirname + "/uploads/" +imgname, buf);
});
// here data.image64 and data.userid --> is the parameter which we pass during socket event request.
For multi part - this may help you.
socket.on('Upload_Image', function(data)
{
var app = require('express')();
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage }).single(data.file);
console.log(data.file);
app.post('/', function (req, res)
{
upload(req,res,function(req,res)
{
if(err)
{
console.log("error uploading file");
}
else
{
console.log("uploaded");
}
});
});
});
Related
I am using body-parser to get info requested from forms, but when I put enctype="multipart/form-data" in the header of the form, the req.body will not working at all.
However, I have used multer lib in order to upload images as follow:
app.post("/", function (req, res, next) {
var button = req.body.button_name;
if (button == "upload") {
var UserId = 2;
var imageUploadedLimited = 3;
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var dir = "./public/images/uploads/";
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
dir = "./public/images/uploads/" + UserId;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
callback(null, dir);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now() + ".jpg");
},
});
const maxSize = 1 * 1000 * 1000;
var upload = multer({
storage: storage,
limits: { fileSize: maxSize },
fileFilter: function (req, file, cb) {
var filetypes = /jpeg|jpg|png/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(
path.extname(file.originalname).toLowerCase()
);
if (mimetype && extname) {
return cb(null, true);
}
cb(
"Error: File upload only supports the " +
"following filetypes - " +
filetypes
);
},
}).array("filename2", imageUploadedLimited);
upload(req, res, function (err) {
if (err) {
res.send(err);
} else {
res.send("Success, Image uploaded!");
}
});
}
});
If I print out the button variable from the second line, will show me undefined value. I know body-parser does not support enctype="multipart/form-data". In this case, how I can see the value from the form?
If you are using multer, it needs to be passed as middleware
// Do Something like this
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'Your path here')
},
filename: function (req, file, cb) {
cb(null, "fileName")
}
})
var upload = multer({
storage: storage,
})
app.post("/" ,upload.any(), function (req, res, next) {
// NOW YOU CAN ACCESS REQ BODY HERE
});
In node a can make something like this with and excel file in my directory.
app.post('/api/xlstojson', function(req, res) {
var workbook = XLSX.readFile('tc2.xls');
var sheet_name_list = workbook.SheetNames;
res.json(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]));
});
I want to test file uploading with postman. There I select POST, form-data, in key I select file instead of text and then in value I upload the tc2.xls file.
In my code I have something like this
app.post('/api/xlstojson', function(req, res) {
var workbook = XLSX.readFile(req.body.file);
var sheet_name_list = workbook.SheetNames;
res.json(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]));
});
But I get TypeError: path must be a string or Buffer. How should I modify my code to make this work?
Update:
I have been trying with multer, but the file does not appear in the folder
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
TypeError: path must be a string or Buffer
You're getting this error because you're not passing the file location. For this to work, you need to pass the location of the file within the upload/ folder
'use strict';
const XLSX = require('xlsx');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
}
});
var upload = multer({ //multer settings
storage: storage
});
function validate(req, res, next) {
if (!req.file) {
return res.send({
errors: {
message: 'file cant be empty'
}
});
}
next();
}
app.post('/api/xlstojson', upload.single('file'), validate, function (req, res) {
const fileLocation = req.file.path;
console.log(fileLocation); // logs uploads/file-1541675389394.xls
var workbook = XLSX.readFile(fileLocation);
var sheet_name_list = workbook.SheetNames;
return res.json({
json: XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]])
});
});
You need to upload the xls file from postman
I am trying to upload an image using express but I am facing two problems, first, whenever I upload the same image again it's not getting uploaded and secondly after uploading any single image a file with image also uploading. Here is my code.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
var file = __dirname +"/images" + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err,data) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
The uploads.single("file") middleware Will handle the file upload. You don't have to specifically fs.read and fs.write the file.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
EDIT: The above code will upload the file with hex string as filename without any extension.
In order to add rename function you need to use diskStorage. Here is the code taken from this github issue page.
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype)); //this is the rename func
});
}
});
var uploads = multer({ storage: storage });
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
Now you can use the uploads variable as middleware as shown in the above snippet.
you can edit the filename: function (req, file, cb) { .. } according to your needs. Now the filename will be, <16characterhexstring>.ext
another way to handle it will be not using middleware and using multer manually with below options :
try {
var storage = multer.diskStorage({
destination: function(request, file, callback) {
//define folder here by fs.mkdirSync(anyDirName);
},
filename: function(req, file, callback) {
callback(null, anyFileName);
},
limits: self.limits
});
var upload = multer({
storage: storage,
fileFilter: function(request, file, callback) {
// here you can filter out what not to upload..
}
}).any();
upload(request, response, callback);
} catch (e) {
}
hope this helps!
I need your help on displaying images stored in MongoDB using Node.JS and express framework.
I've successfully saved the image using this method:
var multer = require('multer');
//var upload = multer({ dest: 'public/Images/' });
var fs = require("fs");
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/Images/')
},
filename: function (req, file, cb) {
//cb(null, file.originalname + '-' + Date.now())
cb(null, Date.now() + '-' + file.originalname);
}
});
var upload = multer({storage: storage});
var user = require('../app/model/user');
app.post('/upload', upload.single('meme'), function (req, res, next) {
if (req.file){
var host = req.hostname;
var filePath = req.protocol + "://" + host + '/' + 'public/Images/' + req.file.originalname;
//console.log(filePath);
var newMeme = new user();
newMeme.meme.imgs = filePath;
newMeme.uploadDate = Date.now();
newMeme.save(function (err) {
if (err)
throw err;
//console('Meme saved');
});
return res.send({
success: true
}) ;
} else {
console.log('failed');
res.send({
success: false
});
}
})
I'm now lost when it comes to displaying the images stored.
These are the stuff I want to display:
please, can someone help? I'm using express JS and ejs as my view engine.
Thanks.
I am new to node JS and i have made function for uploading image from API.
But when i hit the URL from postman using form-data having field name image then in response it shows me.
Here is the postman image
Error uploading file
below is my code
My router.js contain:-
var express = require('express');
var router = express.Router();
var ctrlSteuern = require('../controllers/steuern.controllers.js');
router
.route('/steuern/image_upload')
.post(ctrlSteuern.imageUpload);
in Controller i have:-
var multer = require('multer');
var multiparty = require('multiparty');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './image');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('image');
module.exports.imageUpload = function(req, res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
return res.end("File is uploaded");
});
}
Here is my code for saving image to folder.
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);
});
}
Here is post man request.