how to get an image from android?
I used console.log(request.files.image.originalFilename);
how to read the image in nodejs server.
console.log(request.files.image.path);
can anyone give the solution how to get the file and how to read the file?.
I got an error image is not defined.
var express=require("express");
var app=express();
var multer=require("multer");
var path=require("path");
var fs=require("fs");
var bodyparser=require("body-parser");
var urlencoded=bodyparser.urlencoded({extended:false});
app.use(bodyparser.json({limit: "50mb"}));
app.use(bodyparser.urlencoded({limit: "50mb", extended: true,parameterLimit:50000}));
app.post("/uploadimage",urlencoded,function(request,response)
{
console.log("I got a request");
console.log(request.files.image.originalFilename);
fs.readFile(request.files.image.path,function (err, data)
{
var dirname = "C:/Users/Kishore Baskar/WebstormProjects/Confident";
var newPath = dirname + "/imagesfolder/one.jpg";
fs.writeFile(newPath, data, function (err)
{
if (err)
{
console.log("file not written");
}
else
{
console.log("file written successfully");
}
});
});
});
app.listen(8086,function()
{
console.log("server listen at port 8086");
});
import multer from 'multer';
// Where you want to store file locally
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, file.originalname)
}
})
try{
var upload = multer({
storage: storage,
fileFilter: function (req, file, callback) {
var ext = path.extname(file.originalname);
if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(new Error('Only images are allowed'))
}
callback(null, true)
},
limits:{
fileSize: 1024 * 1024
}
});
} catch(e){
console.log("Error File in file Upload Filter",e);
}
**//storage: storage }).single('file') file is file name object like : file:fileobject from client**
router.post('/uploadImage',multer({ storage: storage }).single('file'),(req,res,next) => {
try {
// Get File Here
console.log(req.file);
} catch(e){
console.log(e)
}
Related
When I upload file using multer nodemon restarts web server. It's fine on my local machine which is windows. It only happens when I start my server on ubuntu machine. What's the problem? My code is here below.
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../public/uploads/'))
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb('Only images! jpeg|jpg|png|gif ');
}
}
const upload = multer({
storage: storage,
limits: { fileSize: 5242880 },
fileFilter: function (_req, file, cb) {
checkFileType(file, cb);
}
});
router.route('/upload').post(protect, upload.array('banner', 12), (req, res, next) => {
console.log(req.files)
if (!req.files) {
res.status(400).json({ success: false, message: 'File not found' });
return;
}
const data = [];
const baseUrl = `THE_URL_FILE_UPLOAD`;
req.files.map((file, idx) => {
data.push({ path: baseUrl + file.originalname })
})
res.status(200).json({ success: true, data })
});
Currently the image gets stored in my upload folder. Since i am new to node.js and multer can anyone guide me on how to store these images to google drive?
https://developers.google.com/drive/api/v3/quickstart/nodejs
When through these link but dont know how to implement it in my project. The code provided in this link uploades an image to google drive but the path of the file has to be harcoded. Can anyone please help me out. I am beginner in back end development.
here is my code for reference
```
const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
//set storage engine
const storage = multer.diskStorage({
destination: "./public/uploads/",
filename: function(req, file, cb) {
cb(null,file.fieldname + "-" + Date.now() + path.extname(file.originalname));
}
});
//init upload
const upload = multer({
storage: storage,
limits: { fileSize: 10000000 },
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
}).single("myImage");
//check file type
function checkFileType(file, cb) {
//Allowed ext
const fileTypes = /jpeg|jpg|png|gif/;
//check ext
const extname = fileTypes.test(
path.extname(file.originalname).toLocaleLowerCase()
);
//check mime
const mimetype = fileTypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb("Error: Images Only!");
}
}
router.get("/", (req, res) => res.render("./index"));
router.post("/upload", (req, res) => {
upload(req, res, err => {
if (err) {
res.render("index", {
msg: err
});
} else {
// console.log(req.file);
// res.send("test");
if (req.file == undefined) {
res.render("index", {
msg: "Error: No File Selected!"
});
} else {
res.render("index", {
msg: "File uploaded!",
file: `uploads/${req.file.filename}`
});
}
}
});
});
module.exports = router;
```
I am using multer and it works fine in the http object, here is the code:
server = http.createServer(function(req, res){
var upload = multer({ storage : multerhelper.storage}).single('userFile');
upload(req, res, function(err) {
if(err)
console.log("Error uploading the file");
});
});
The moment I take this piece of code outside of the http object inside another file, it doesn't work anymore.
handlers._users.post = function(req, res, data, callback){
var upload = multer({ storage : multerhelper.storage}).single('userFile');
upload(req, res, function(err) {
if(err)
console.log("Error uploading the file");
callback(400, {'Message' : 'Done'});
});
});
Your help is appreciated.
You can make a file which will have the multer logic and export this file so that you can get the multer functionality.
example:
const multer = require("multer");
// store the file reference through multer
const storage = multer.diskStorage({
destination: function (req, file, callback) {
//Where file should be store
callback(null, __base + "/public/uploads");
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
//make sure file is image as the jpeg or png
const fileFilter = (req, file, callback) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png" || file.mimetype === 'application/octet-stream') {
callback(null, true);
}
callback(null, false);
};
export const upload = multer({
storage,
limits: {
fileSize: 1024 * 1024 * 5000
},
fileFilter
});
Now import this file as
import {
upload
} from "/filepath";
for some reason the fileFilter on multer is not getting called.
here is my Controller (i am using express routers)
const express = require('express');
const router = express.Router();
const UploadController = require('../controllers/UploadController');
router.route('/upload').post(UploadController.upload);
module.exports = router;
and this is the controller
const multer = require('multer');
const fs = require('fs');
module.exports = {
upload: function (req, res) {
let storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log('here');
const filesDir = './uploads/' + req.body.ref;
if (!fs.existsSync(filesDir)) {
fs.mkdirSync(filesDir);
}
cb(null, filesDir);
},
filename: function (req, file, cb) {
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, req.body.type + '-' + Date.now() + '.' + extension);
},
fileFilter : function (req, file, cb) {
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
}
})
const upload = multer({ storage: storage }).single('file');
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
res.send({
error: err
});
} else if (err) {
res.send({
error: err
});
}else{
res.send({
file: req.file,
body: req.body
});
}
});
}
}
I have following issues:
The fileFilter function is not even called so its not validating files
the req.body on the upload function (upload: function (req, res)) is empty it is only available in diskStorage and last upload function (upload(req, res, function (err)) so i cannot validate the body data also.
I had the same problem. the fileFilter function has to be defined inside multer, not inside the diskStorage function.
To make it a bit more readable I defined the storage and filter in variables instead of making everything inside the multer call.
// storage settings
const multerStorage = multer.diskStorage({
destination: function(req, file, next) {
next(null, './public/files');
},
filename: function(req, file, next) {
const sanitizedName = file.originalname
.replace('/[^a-z0-9\./gi', '-')
.replace('/-{2,}/g', '-')
.toLowerCase();
const name = Date.now() + '-' + sanitizedName;
// sending the file name to be stored in the database
req.body.filename = name;
next(null, name);
},
limits: {
fileSize: 25000000
}
});
// filter function
const multerFilter = function(req, file, cb) {
const ext = path.extname(file.originalname).toLowerCase();
if (ext !== '.pdf') {
cb(new Error('File must be in PDF format.'));
}
cb(null, true);
}
And then applying the storage settings and filter function to multer:
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter
});
I have written the code for multer as shown below:
const storage = multer.diskStorage({
destination(req, file, callback) {
callback(null, './public/images')
},
filename(req, file, callback) {
profile_image = `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`;
callback(null, profile_image)
}
});
const xyz = (req, res) => {
upload = multer({
limits: {
fileSize: 1000000,
files: 2
},
storage,
fileFilter(req, file, callback) {
const ext = path.extname(file.originalname);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(res.end('Only images are allowed'), null)
}
callback(null, true);
}
}).any();
upload(req, res, err => {
})
upload starts working the moment there is no error in uploading file, but not when the file is uploaded successfully in the disk. So is there any other callback through which I can know when the file is successfully uploaded in the disk?
Try this it might solves your issue. You can check success in upload function in below example.
var Express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var app = Express();
app.use(bodyParser.json());
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Images");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage: Storage }).array("imgUploader", 3); //Field name and max count
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/api/Upload", function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end("Something went wrong!");
}
return res.end("File uploaded sucessfully!.");
});
});
app.listen(2000, function (a) {
console.log("Listening to port 2000");
});
Check in your upload function like this
upload(req, res, err => {
if (err) {
res.end("Something went wrong!");
}
res.end("File uploaded sucessfully!.");
}