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 })
});
Related
NOTE: I have tried and seen other similar issues but none resolved my problem thus posting again, thanks.
Hey everyone! I am trying to access the images uploaded in a folder at the backend/uploads directory which is marked as static but its not working as expected.
uplaodRoutes.js
const path = require("path");
const express = require("express");
const multer = require("multer");
const router = express.Router();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, "backend/uploads/");
},
filename(req, file, cb) {
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
);
},
});
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb("Images only!");
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, CB);
},
});
router.post("/", upload.single("image"), (req, res) => {
req.file.size = req.file.size / 1000;
res.send(req.file);
});
module.exports = router;
server.js
app.use(
"/uploads",
express.static(path.join(path.resolve(), "backend/uploads"))
);
as we can see we cannot access it in browser.
const upload = multer({
**storage: fileStorageEngine,** add fileStorageEngine Parameter
storage: fileStorageEngine,
fileFilter: function (req, file, cb) {
**change from CB to cb**
checkFileType(file, cb);
},
});
I'm trying to upload mp4 file by using multer in node.js
(View)VideoUploadPage.js
import React, { useState } from "react";
import Axios from "axios";
function VideoUploadPage() {
const onDrop = (files) => {
let formData = new FormData();
const config = {
header: { "content-type": "multipart/form-data" },
};
formData.append("file", files[0]);
console.log(files);
Axios.post("/api/video/uploadfiles", formData, config).then((response) => {
if (response.data.success) {
console.log(response.data);
} else {
alert("비디오 업로드를 실패 했습니다.");
}
});
};
}
(Server)
video.js
const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const ffmpeg = require("fluent-ffmpeg");
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/");
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
},
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname);
if (ext !== ".mp4") {
return cb(res.status(400).end("only mp4 is allowed"), false);
}
cb(null, true);
},
});
const upload = multer({ storage: storage }).single("file");
router.post("/uploadfiles", (req, res) => {
upload(req, res, (err) => {
if (err) {
return res.json({ success: false, err });
}
return res.json({
success: true,
url: res.req.file.path,
fileName: res.req.file.filename,
});
});
});
At the video.js destination: (req, file, cb) => {
cb(null, "uploads/")
} <----- I can check which file is going to upload with console.log(response.data), but there is no mp4 file in the "uploads" folder.
When I changed "uploads/" to my local directory path, mp4 file is on the uploads folder ....
ex: "C://~~~/uploads"
Any idea?
use path.resolve('./uploads') to resolve a sequence of path-segments to an absolute path.
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.resolve('./uploads'); // path of the upload folder
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`);
},
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname);
if (ext !== ".mp4") {
return cb(res.status(400).end("only mp4 is allowed"), false);
}
cb(null, true);
},
});
You can use path.resolve(process.cwd() + 'path till upload folder');
for eg:
path.resolve(process.cwd() + '/uploads');
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;
```
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'm using multer to upload files. everything is goung fine but fileFilter is not working. I've no idea where i'm going wrong.
routes.js
var multer = require('multer');
// Multer diskStorage setting
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
filFilter: function (req, file, cb) {
var typeArray = file.mimetype.split('/');
var fileType = typeArray[1];
if (fileType == 'jpg' || fileType == 'png') {
cb(null, true);
} else {
cb(null, false)
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
var upload = multer({ storage: storage });
router.post('/add', upload.single('photo'), function(req, res){
console.log('uploaded');
}
Multer also uploads files other than allowed. Any idea?
fileFilter must be defined in multer's options object rather than diskStorage
const uploadFilter = function(req, file, cb) {
// filter rules here
}
const upload = multer({
storage: storage,
fileFilter: uploadFilter,
});
const storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
fileFilter: function (req, file, cb) {
const extension = path.extname(file.originalname).toLowerCase();
const mimetyp = file.mimetype;
if (
extension !== '.jpg' ||
extension !== '.jpeg' ||
extension !== '.png' ||
mimetyp !== 'image/png' ||
mimetyp !== 'image/jpg' ||
mimetyp !== 'image/jpeg'
) {
cb('error message', true);
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
},
});
const upload = multer({ storage: storage });
router.post('/add', upload.single('photo'), function (req, res) {
console.log('uploaded');
});
i think this will help
You have a typo at your fileFilter; you've named it filFilter.
Could you change your code to the following and tell us if it worked out?
var multer = require('multer');
// Multer diskStorage setting
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
fileFilter: function (req, file, cb) {
var typeArray = file.mimetype.split('/');
var fileType = typeArray[1];
if (fileType == 'jpg' || fileType == 'png') {
cb(null, true);
} else {
cb(null, false)
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
var upload = multer({ storage: storage });
router.post('/add', upload.single('photo'), function(req, res){
console.log('uploaded');
}