I want to upload files from the form data in react which is being posted by axios like this.
const addNewProduct = () => {
const newProduct = {
name: name,
cost: cost,
size: size,
color: color,
material: material,
discount: discount,
description: description,
category: category
};
const nulls = Object.values(newProduct).filter(p => p === null);
if(nulls.length === 0 && images.imageFiles) {
let productFormData = new FormData();
productFormData.append('productInfo', JSON.stringify(newProduct));
productFormData.append('productImages', images.imageFiles);
const addUrl = "http://localhost:8080/cpnl/addproduct";
axios({
method: "POST",
url: addUrl,
data: productFormData,
headers: { "Content-Type": "multipart/form-data" }
})
.then((response) => {
console.log(response.data.msg);
})
.catch((response) => {
console.error(response);
});
}else {
Notiflix.Notify.Warning("Check your inputs!");
console.log(nulls);
console.log("product: \n" + JSON.stringify(newProduct));
}
};
then I want to upload images with multer to images folder. this is my code:
const storage = multer.diskStorage({
destination: "./public/images",
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).array("productImages", 5);
function checkFileType(file, cb) {
// Allowed ext
const filetypes = /jpeg|jpg|png/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Images Only!');
}
}
//receive form data from front-end and add new product to database
router.post('/addproduct', async (req, res) => {
upload(req, res, (err) => {
if(err) {
res.status(400).json({
msg: err
});
} else {
if(req.files == undefined) {
res.status(400).json({
msg: "Error: No file selected! please contact the developer."
});
} else {
data = req.body.productInfo;
res.status(200).json({
msg: "Files uploaded!"
});
console.log( "images: " + req.files);
console.log("data" + data);
}
}
});
});
first problem: I'm getting image files inside req.body.productImages and not inside req.files
second problem: when I send the request node js throws me this error:
TypeError: upload is not a function
why everything is messed up!?
Edit: I restarted the server and now I'm getting data but the files are not being uploaded. no error is shown.
UPDATE: second problem fixed
First Problem : You have used .array("productImages", 5); in your upload function. use .array("files", 5); to get the file in req.files.
Second Problem : I guess there is some typo error in your code upload(req, res, (err)... there is one extra bracket it should be only upload(req,res,err )...
Related
I am making a guide's update controller which include name, email, password, avatar[image] and guidelicence[pdf]. It gives the error cannot read undefined at(0) but the same logic runs for signup. I am using multer and cloudinary for form data, and have been stuck for 2 days.
Update Route
routes.put(
"/:userID",
upload.fields([
{ name: "avatar", maxCount: 1 },
{ name: "guidelicense", maxCount: 1 },
]),
update
);
Update Controller
exports.update = async (req, res) => {
try {
// handle the form data
const {
fullname,
password,
email,
address,
isAvalaible,
phonenumber,
cnic,
} = req.body;
// handle the image file
const avatar = req.files.avatar[0];
console.log(req.files.avatar[0]);
// handle the PDF file
const guideLicense = req.files.guidelicense[0];
console.log(req.files.guidelicense[0]);
// upload the image to Cloudinary
cloudinary.uploader.upload(
avatar.path,
{ resource_type: "image" },
(err, image) => {
if (err) throw err;
// store the image URL in the database
const avatarUrl = image.url;
// upload the PDF to Cloudinary
cloudinary.uploader.upload(
guideLicense.path,
{ resource_type: "raw" },
(err, file) => {
if (err) throw err;
// store the PDF URL in the database
const guideLicenseUrl = file.url;
// update the guide's information in the database
Guides.findOneAndUpdate(
{ email },
{
fullname,
password,
avatarUrl,
guideLicenseUrl,
address,
isAvalaible,
phonenumber,
cnic,
},
(err, guide) => {
if (err) throw err;
res.status(200).json({ message: "Guide updated successfully" });
}
);
}
);
}
);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
multer configuration
if (!fs.existsSync("./uploads")) {
fs.mkdirSync("./uploads");
}
// Multer config
module.exports = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
}),
limits: { fileSize: 1024 * 1024 * 5 },
fileFilter: (req, file, cb) => {
let ext = path.extname(file.originalname);
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png" && ext !== ".pdf") {
cb(new Error("File type is not supported"), false);
return;
}
cb(null, true);
},
});
i wanted to get guide updated successfully but got
{
"message": "Cannot read properties of undefined (reading '0')"
}
error
You need to parse the req before accessing it.
Use the parsed "request" to access the data.
const request = JSON.parse(req);
I am trying to upload an image from my front end to the backend but it it doesn't send the image in the request
It says that the formdata is empty and it says that there's no image found, where is the problem and how can I fix this error?
Here is the code from the Frontend made in react:
const [userInfo, setuserInfo] = useState({
file:[],
filepreview:null,
});
const handleInputChange = (event) => {
setuserInfo({
...userInfo,
file:event.target.files[0],
filepreview:URL.createObjectURL(event.target.files[0]),
});
}
const [isSucces, setSuccess] = useState(null);
const submit = async () =>{
const formdata = new FormData();
formdata.append('avatar', userInfo.file);
console.log(formdata)
Axios.post("http://localhost:4000/imageupload", formdata,{
headers: { "Content-Type": "multipart/form-data" }
})
.then(res => { // then print response status
console.warn(res);
if(res.data.success === 1){
setSuccess("Image upload successfully");
}
})
}
The code of the Backend made in NodeJS:
const storage = multer.diskStorage({
destination: path.join(__dirname, './temp', 'uploads'),
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
app.post('/imageupload', async (req, res) => {
try {
// 'avatar' is the name of our file input field in the HTML form
let upload = multer({ storage: storage}).single('avatar');
upload(req, res, function(err) {
// req.file contains information of uploaded file
// req.body contains information of text fields
if (!req.file) {
return res.send('Please select an image to upload');
}
else if (err instanceof multer.MulterError) {
return res.send(err);
}
else if (err) {
return res.send(err);
}
const classifiedsadd = {
image: req.file.filename
};
res.send("ok")
});
}catch (err) {console.log(err)}
})
Edit:
Multer is essentially a nodejs router,i.e. a function that can be pipelined between your HTTP request and HTTP response.
I think that you should first make multer analyze your HTTP content and to actually populate the req.file before actually evaluate express parsers do their job.
const storage = multer.diskStorage({
destination: path.join(__dirname, './temp', 'uploads'),
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
let upload = multer({ storage: storage});
app.post('/imageupload', upload.single('avatar'), async (req, res) => {
try {
// 'avatar' is the name of our file input field in the HTML form
// req.file contains information of uploaded file
// req.body contains information of text fields
if (!req.file) {
return res.send('Please select an image to upload');
}
else if (err instanceof multer.MulterError) {
return res.send(err);
}
else if (err) {
return res.send(err);
}
const classifiedsadd = {
image: req.file.filename
};
res.send("ok")
}catch (err) {console.log(err)}
})
I am assuming that your upload code is working. Have you tried to read the HTTP request from your browser to see that the image has been correctly attached to the request?
Because probably the issue lies in the fact that you are not actually parsing the image.
const file = new File(userInfo.file, "avatar.png", {
type: 'image/png' // choose the appropriate
});
const formdata = new FormData();
formdata.append('avatar', file);
console.log(formdata)
I built a web app and want to resize my images to be smaller for better quality to my profile pictures. I am using "multer" for upload picture and sharp package for resizing.
For some reason i get this error:
"[0] [Error: D:\DevConnectors\public\resized\5f4f4e0bb295ba36042536bf.jpg: unable to open for write
[0] windows error: The storage control block address is invalid."
My code:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR)
},
filename: (req, file, cb) => {
var typeFile = file.originalname.split(".").pop()
const fileName = req.user.id + "." + typeFile
cb(null, fileName)
},
})
var upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (
file.mimetype == "image/png" ||
file.mimetype == "image/jpg" ||
file.mimetype == "image/jpeg"
) {
cb(null, true)
} else {
return cb(new Error("Only .png, .jpg and .jpeg format allowed!"), false)
}
},
})
const Profile = require("../../moduls/Profile")
const User = require("../../moduls/User")
//#route GET/api/profile/me
//#desc Get current users profile
//#access Private
router.post(
"/upload",
[auth, upload.single("imageProfile")],
async (req, res) => {
try {
console.log(req.file)
const { filename: image } = req.file
await sharp(req.file.path)
.resize(150)
.jpeg({ quality: 50 })
.toFile(path.resolve(req.file.destination, "resized", image))
fs.unlinkSync(req.file.path)
const url = req.protocol + "://" + req.get("host")
let user = await User.findById(req.user.id)
const profile = await Profile.findOne({ user: req.user.id })
//Update
if (user) {
user.avatar = url + "/public/" + req.file.filename
await user.save()
return res.json(profile)
}
} catch (err) {
console.log(err)
}
}
)
This happens at this line :
path.resolve(req.file.destination,'resized',image))
What am i doing wrong? i am using sharp docs.
Try this
Configuration of multer ( change it according to your needs)
import multer from "multer";
import sharpe from "sharp";
const upload = multer({ //multer configuration
//dest: "avatars", //so that buffer is available in route handler
limits: {
fileSize: 1000000,
},
fileFilter(req, file, cb) { // object method shorthand syntax
if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) { //.match for using regex b/w (//)
return cb(new Error("Please upload a IMAGE"));
}
cb(undefined, true);
},
});
handle sharp in your route handle like this.
router.post(
"path",
upload.single("avatar"),
async (req, res) => {
const buffer = await sharpe(req.file.buffer)
.png()
.resize({
width: 300,
height: 300
})
.toBuffer();
req.user.avatar = buffer;
await req.user.save();
res.send();
},
(error, req, res, next) => {
//to tell express this how mutler/s error should be handled
res.status(400).send({
error: error.message,
});
}
);
I had the same problem, and in my case the issue was that the directory (in your case "resized") didn't exist yet. So either create it manually or programmatically like this:
const targetPath = path.resolve(req.file.destination, 'resized')
if (!existsSync(targetPath)) {
mkdirSync(targetPath);
}
await sharp(...)
My goal is the following:
I want to get user uploaded PDF, extract the Text from within that PDF, assign the text to an array object. Once this is done I want to upload that file to an S3 bucket. Right now I am able to to do the first part without much issue. The reason why I am doing the local upload in the first place is so I can do the text extraction from PDF. These methods work on their own. If i want to upload to S3 it will and the database gets populated with the link for me to show it on the front-end but the BulletinMetaText field does not get populated with the extract text.
What way should I go about doing this?
If I have not been clear please let me know what more I can provide..
Multer methods:
let uploadToS3 = multer({
storage: multerS3({
s3: s3,
acl: "private",
bucket: env == "production" ? "xxxx" : "xxxx",
// metadata: function(req, file, cb) {
// console.log(file);
// console.log(req.body);
// cb(null, Object.assign({}, req.body));
// },
key: function(req, file, cb) {
// console.log(file);
cb(null, `${new Date().getFullYear()}/${file.originalname}`);
}
})
}).array("files");
// }).any();
var tempStorage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "client/v1.7/src/assets/pdf/");
},
// By default, multer removes file extensions so let's add them back
filename: function(req, file, cb) {
cb(null, `${file.originalname}`);
}
});
var uploadToLocal = multer({ storage: tempStorage }).array("files");
let delay = time => {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve("DONE");
}, time);
});
};
Node/express Backend
if (req.params.type === "files") {
uploadToLocal(req, res, function(err) {
if (err) {
next({
status: 500, //Server Error
statusMessage: "Error: Failed to save file ",
catchError: err //System error
});
} else {
//TODO
let {
bulletinID,
bulletinUUID,
bulletinActive,
bulletinType,
bulletinCode,
bulletinGroup,
bulletinEn,
bulletinFr,
bulletinTitleEn,
bulletinDescriptionEn,
bulletinTitleFr,
bulletinDescriptionFr,
metaStringTags,
bulletinPermission
} = req.body.model;
uploadToS3(req, res, function(err) {
console.log("upload2Req");
console.log(req.body);
let bulletinFileEn,
bulletinFileFr = "";
// console.log("req.files");
console.log(req.files);
req.files.forEach(file => {
if (file.originalname && file.originalname.includes("_en")) {
console.log("file");
console.log(file);
console.log(file.key);
bulletinFileEn = file.key;
}
if (file.originalname && file.originalname.includes("_fr")) {
bulletinFileFr = file.key;
}
});
console.log(bulletinFileEn);
console.log(bulletinFileFr);
extract(
"client/v1.7/src/assets/pdf/test.pdf",
// req.files.originalname,
{ splitPages: false },
function(err, text) {
if (err) {
console.log(err);
return;
}
console.log("text");
// console.log(text);
bulletinMetaText = text;
if (err) {
next({
status: 500, //Server Error
statusMessage: "Error: Failed to save file locally ",
catchError: err //System error
});
} else {
// !~
let newBulletin = {
bulletinID: bulletinID ? bulletinID : "NULL",
bulletinUUID: bulletinUUID ? bulletinUUID : uuid(),
bulletinActive: bulletinActive ? bulletinActive : true,
postedByUserID: req.user.id,
postedByUserUUID: req.user.userUUID,
bulletinType: bulletinType,
bulletinCode: bulletinCode,
bulletinGroup: bulletinGroup,
bulletinEn: bulletinEn ? true : false,
bulletinFr: bulletinFr ? true : false,
//English Bulletin - File/Link
bulletinTitleEn: bulletinTitleEn,
bulletinDescriptionEn: bulletinDescriptionEn,
bulletinLinkEn: null,
bulletinFileEn: bulletinFileEn,
//French Bulletin - File/Link
bulletinTitleFr: bulletinTitleFr,
bulletinDescriptionFr: bulletinDescriptionFr,
bulletinLinkFr: null,
bulletinFileFr: bulletinFileFr,
metaStringTags: metaStringTags,
bulletinPermission: bulletinPermission,
bulletinTextScrape: bulletinMetaText
};
console.log(newBulletin);
InsertOrUpdateBulletin(newBulletin, req.user)
.then(result => {
res.status(200).json({
data: result,
status: 200, //Created
statusMessage: "Success: Bulletin Created"
});
})
.catch(error => {
next({
status: 500, //Server Error
statusMessage: "Error: Failed to save Bulletin ",
catchError: error //System error
});
});
}
}
);
});
}
});
}
This might help (keyword: might) but it uses express-fileupload. Still allows for server side manipulation of the data.
https://link.medium.com/U1SdsoHMy2
I am giving post request /product/create with some value and an image.
if I console every value before
upload(req, res, (err) => {})
it is showing properly with out image info.
if I receive the value after upload(req, res, (err) => {})
No value is showing.
Full post request code:
app.post('/product/create', (req, res) => {
let filename;
upload(req, res, (err) => {
if(err){
res.render('index', {
msg: err
});
} else {
if(req.file == undefined){
res.render('index', {
msg: 'Error: No File Selected!'
});
} else {
res.render('index', {
msg: 'File Uploaded!',
filename = req.file.filename;
});
}
}
});
const product = {
title : req.body.title,
desc : req.body.desc,
image : filename,
}
});
configuring Multer:
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).single('myImage');
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('Error: Images Only!');
}
}
Multer does not support 'req.file.filename' outside upload function. As filename, originalname, fieldname etc is inbuild API of multer. It is limited to upload function only.
Now, if you are trying to upload product values inside database then you have to create an insert function inside multer upload function only.