The second file isn't uploading to FTP server [node.js + multer] - javascript

I have problem with uploading a images to my FTP server. The problem is that the first array of photos that I'm uploading is uploaded successfully but second time If I'm trying to upload something it isn't working and I don't know why. To uploading files I'm using multer-sftp package.
Code:
const storage = sftpStorage({
sftp: {
host: process.env.FTP_HOST,
user: process.env.FTP_USER,
password: process.env.FTP_PASSWORD,
port: 22,
},
destination: (req: any, file: any, callback: any) => {
callback(null, "");
},
filename: (req: any, file: any, callback: any) => {
callback(null, `${Date.now()}-${file.originalname}`);
},
});
const fileFilter = (
req: Request,
file: Express.Multer.File,
cb: FileFilterCallback
) => {
if (
file.mimetype === "image/png" ||
file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg" ||
file.mimetype === "image/webp"
) {
cb(null, true);
} else {
cb(null, false);
}
};
app.use(
multer({ storage: storage, fileFilter: fileFilter }).array("images", 8)
);

Related

cant get files using multer in node js (req.file is undefined)

i use multer package with node and react and i send a file to node js backend, but always its undefined..
This is React
<div className="file-field input-field">
<div className="btn">
<span>File</span>
<input
type="file"
name="image"
id="image"
onChange={changedImageUpload}
/>
</div>
<div className="file-path-wrapper">
<input className="file-path validate" />
</div>
</div>
and that is onChange file handling method in there i just get first console.log but second and third is not printed
const changedImageUpload = (e) => {
const file = e.target.files[0];
const formData = new FormData();
formData.append("image", file);
console.log(formData, file);
try {
const config = {
Headers: {
"Content-Type": "multipart/form-data",
},
};
axios
.post("/uploads", formData, config)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
} catch (err) {
console.log(err);
}
};
and its Node codes and multer configure
import express from "express";
import multer from "multer";
const route = express.Router();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(
null,
new Date().toISOString().replace(/[\/\\:]/g, "_") + file.originalname
);
},
});
const multerFilter = (req, file, cb) => {
if (
file.mimetype === "image/png" ||
file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg"
) {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({ storage: storage, fileFilter: multerFilter });
route.post("/uploads", upload.single("image"), (req, res) => {
try {
// res.send(`/${req.file.path}`);
console.log(req.file);
} catch (err) {
console.log(err);
}
});
and import in app.js
import uploadRoutes from "./Routes/uploadRoutes.js";
app.use(uploadRoutes);
const __dirname = path.resolve();
app.use("/images", express.static(path.join(__dirname, "/images")));
so at printing formData i always get empty object, and if i print req.file i get an undefined in node js
Your filter function is wrong. You are comparing the mimeType to things like jpg which isn't a real MIME type, so your files are always filtered out.
You need to compare to image/png and image/jpeg instead.

Node + Express + Multer: upload array where some elements are null?

I want to upload an array of files, but some elements can be null/undefined. Multer ignores the null files. Is there a way to make Multer maintain the index of non-null files?
E.g. if I upload an array where the first element is null and the second is a file:
------WebKitFormBoundarydFfDIpmAwbAA7GSS
Content-Disposition: form-data; name="photos"
null
------WebKitFormBoundarydFfDIpmAwbAA7GSS
Content-Disposition: form-data; name="photos"; filename="photo.jpg"
Content-Type: image/jpeg
In my request handler, I'd receive an array with 1 element. I wouldn't know if this was the first or second element:
[
{
fieldname: 'photos',
originalname: 'photo.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: '/tmp',
filename: '24c944fd7975c503c4cc4add4f447aaf',
path: '/tmp/24c944fd7975c503c4cc4add4f447aaf',
size: 837080
}
]
Is there a way to make Multer make the first array element null?
i don't know your code but it should be multer settings
const fileFilter = (req, file, cb) => {
if(file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
cb(null, true)
}else{
cb(new Error('should be png or jpeg'), false)
}
}
const multerStorage = multer.memoryStorage();
const upload = multer({
storage: multerStorage,
fileFilter: fileFilter
});
it should be coming request;
images => request payload data
35 => coming image quantity
router.put('/update', upload.array("images", 35), (req, res)
I hope it helped

NodeJS Multer unable to catch eroor

How do I catch the error invoked and return a res status msg? I am unable to catch any error in userController.uploadFile and if I tried to do a upload(req,res (err) in the routes.post, req is not defined.
var storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, url);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
}).single('file');
let upload = multer({
storage: storage,
limits: { fileSize: maxSize },
fileFilter: (req, file, cb) => {
console.log(file);
if (file.mimetype !== 'image/jpeg' || file.mimetype !== 'image/png') {
return cb(new Error('Only jpeg images allowed'))
}
cb(null, true)
}
});
routes.post('/fileupload', upload, userController.uploadFile);
I think we can get this to work with a little tweaking. I've made these changes and tested with a few images.
Your user controller will look a little different, but something like this should work.
I've updated to pass any file too large error to the controller, again this will be in the req.uploadError property, so you can handle as you like.
const userController = {
uploadFile(req, res) {
if (req.uploadError) {
res.status(400).send("An error occurred - " + req.uploadError.message);
} else {
res.status(201).send("All good");
}
}
}
var storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, url);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
});
let upload = multer({
storage: storage,
limits: { fileSize: maxSize },
fileFilter: (req, file, cb) => {
console.log(file);
if (file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
cb(new Error('Only jpeg or png images allowed'));
} else {
cb(null, true);
}
}
}).single('file');
routes.post('/fileupload', (req, res, next) => {
upload(req, res, err => {
req.uploadError = err;
next();
})
}, userController.uploadFile);

Why am I getting "ENOENT: no such file or directory, open" when trying to save an image through multer's storage?

I'm trying to use multer to save an image to my back-end, and more specifically, to public/images/servers folder. Sadly I get an error:
[Error: ENOENT: no such file or directory, open 'C:\MAMP\htdocs\Chat Backend\public\images\servers\2020-08-07T12:33:31.556Z-aohan-chen-.jpg'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\MAMP\\htdocs\\Chat Backend\\public\\images\\servers\\2020-08-07T12:33:31.556Z-aohan-chen-.jpg',
storageErrors: []
}
I'm not sure why it says that there is no such file or directory when everything up until here exists - 'C:\MAMP\htdocs\Chat Backend\public\images\servers'. The only thing left is for multer to save the image in the servers folder.
var multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/images/servers')
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + '-' + file.originalname)
}
})
var fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
cb(null, true)
} else {
cb(null, false)
}
}
app.use(multer({ storage: storage, fileFilter: fileFilter }).single('image'));

How to save pdf file to s3 and on local as well in node js

i am stuck in something that i am unable to solve. I am uploading the file and getting it through req.files. I have added middleware which uploads the file to S3. I tried everything but cannot do it. Upload to S3 is working fine but it isn't saving the file in local path. When i try through fs.writeFile it saves the file which is corrupted.
can someone help me?
middleware function
uploadToS3bucket: (path) => {
return multer(
{
storage: multerS3({
s3: s3,
acl: 'public-read',
bucket: AWS_BUCKET_NAME,
contentType: multerS3.AUTO_CONTENT_TYPE,
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
const params = Object.keys(req.params).map(key => {
return req.params[key]
}).join('/');
const key = path + '/' + params + (params.length > 0 ? '/' : '') + shortUUID.generate() + "-" + file.originalname;
cb(null, key)
}
})
}
)
}
route
router.post('/resume', uploadToS3bucket('temp').fields([
{name: 'resume', maxCount: 1}
]), resumeCtrl.getUserResume);
i tried
// in metadata function
fs.writeFile('python/resume_parser/data/input/resume/' + file.originalname, file, (err) => {
if (err) throw err;
});
and
request({uri: 'http://localhost:3000/v1/user/resume', headers: { 'Content-type' : 'applcation/pdf', 'encoding': 'binary' }} , function (error, response, body) {
if (!error) {
fs.writeFile("python/resume_parser/data/input/resume/"+ file.originalname, body , function (err) {
});
}
})
it is saving the pdf but that is corrupted.
can someone help me?
thanks

Categories

Resources