I have a problem uploading an image file to my server, I watched some tutorials on YouTube about multer and I do exactly the same thing that is done in the tutorial and for whatever reason, I get an error: (“Cannot read property ‘buffer’ of undefined”), and req.file is also undefined. I googled for the error and found some people having the same issue and I tried to solve it like them, but it didn’t work for me.
COMPONENT Data App
JavaScript
x
13
13
1
newPostByUser(token, formData) {
2
return (async () =>
3
await call(`${this.url}/lost`, {
4
method: "POST",
5
headers: {
6
Authorization: `Bearer ${token}`,
7
"Content-Type": "multipart/form-data",
8
},
9
body: formData,
10
timeout: this.timeout,
11
}))();
12
},
13
COMPONENT ImageParse
JavaScript
1
33
33
1
const path = require("path");
2
const multer = require("multer");
3
const storage = multer.memoryStorage();
4
const limits = { fileSize: 2000000 };
5
const upload = multer({
6
storage,
7
limits,
8
fileFilter(req, file, cb) {
9
var filetypes = /jpeg|jpg|png|gif/;
10
const mimetype = filetypes.test(file.mimetype);
11
const extname = filetypes.test(
12
path.extname(file.originalname).toLocaleLowerCase()
13
);
14
if (mimetype && extname) {
15
return cb(null, true);
16
}
17
cb(
18
"Error: File upload only supports the following filetypes - " + filetypes
19
);
20
},
21
}).single("image");
22
23
function imageParse(req, res, next) {
24
upload(req, res, function (err) {
25
if (err) {
26
return res.status(422).json({ error: err.message });
27
}
28
next();
29
});
30
}
31
32
module.exports = imageParse;
33
COMPONENT Route
JavaScript
1
38
38
1
require("dotenv").config();
2
const express = require("express");
3
const logic = require("../logic");
4
const auth = require("./auth");
5
const imageParse = require("../utils/imageParse");
6
const literals = require("../i18n/literals");
7
8
const router = express.Router();
9
10
const { research_newPost_messageConfirm } = literals;
11
12
router.post("/lost", auth, imageParse, (req, res) => {
13
console.log(req.buffer);
14
const {
15
file: { buffer },
16
body: { userId, category, name, age, city, description, lang },
17
} = req;
18
(async () => {
19
try {
20
const user = await logic.newResearch(
21
buffer,
22
userId,
23
category,
24
name,
25
age,
26
city,
27
description,
28
lang
29
);
30
res.status(201).json({ message: research_newPost_messageConfirm[lang] });
31
} catch ({ message }) {
32
res.status(400).json({ error: message });
33
}
34
})();
35
});
36
37
module.exports = router;
38
COMPONENT Logic api
JavaScript
1
51
51
1
const streamifier = require("streamifier");
2
const cloudinary = require("cloudinary").v2;
3
const { Research } = require("../models");
4
const {
5
CLOUDINARY_API_KEY,
6
CLOUDINARY_SECRET_KEY,
7
CLOUDINARY_NAME,
8
} = require("../utils/config");
9
const { logic_newPost_messageError} = require("../i18n/literals");
10
11
const logic = {
12
newResearch(buffer, userId, category, name, age, city, description, lang) {
13
try {
14
return (async () => {
15
cloudinary.config({
16
cloud_name: CLOUDINARY_NAME,
17
api_key: CLOUDINARY_API_KEY,
18
api_secret: CLOUDINARY_SECRET_KEY,
19
});
20
21
const image = await new Promise((resolve, reject) => {
22
const uploadStream = cloudinary.uploader.upload_stream(
23
(err, image) => {
24
if (err) throw new LogicError("Image could not be uploaded");
25
resolve(image);
26
}
27
);
28
streamifier.createReadStream(buffer).pipe(uploadStream);
29
});
30
const newPost = await Research.create({
31
owner: userId,
32
category,
33
name,
34
age,
35
city,
36
description,
37
image: image.secure_url,
38
});
39
40
if (!newPost) throw new Error(`${logic_newPost_messageError[lang]}`);
41
console.log("api", newPost);
42
return newPost;
43
})();
44
} catch (error) {
45
console.log(error);
46
}
47
},
48
};
49
50
module.exports = logic;
51
Advertisement
Answer
it is not req.buffer
it is req.file.buffer