req.files is undefined using express-fileupload - node.js

I am creating a blog so, wanted to upload an image for each post. I used express-file upload for this purpose. Using nodejs I have done the following to save the image sent from the client-side in MongoDB. When I print the value of req.files in the console I get undefined.
exports.addPost = (req, res) => {
const file = req.files.file
const post = new Blog()
post.title = req.body.title
post.des = req.body.des
post.file = file
post.save((err, doc) => {
if (!err) {
res.send(doc)
} else {
console.log(err)
}
})
}
In react I have Addpost.js that sets the state and handles the form submit as follows:
const Addpost=()=> {
const [title, settitle] = useState('')
const [des, setdes] = useState('')
const [file, setfile] = useState('');
const {addPost}=useContext(Globalcontext)
const handleSubmit = (e)=>{
e.preventDefault()
const formData = new FormData()
formData.append('file',file)
const addedValue={
title,
des,
formData
}
addPost(addedValue)
settitle('')
setdes('')
setfile('')
}
const onChange=(e)=>{
const file=e.target.files[0]
setfile(file)
}
return (
<div>
<form onSubmit={handleSubmit} encType="multipart/form-data">
<input type="text" name="title" value={title} onChange={(e)=>settitle(e.target.value)}/>
<input type="text" name="des"value={des} onChange={(e)=>setdes(e.target.value)}/>
<input type="file" name="file" onChange={onChange}/>
<button type='submit' value='submit'>Add Post</button>
</form>
</div>
)
}
The AXIOS post request is sent as:
function addPost(postdetail) {
axios.post('http://localhost:4000/blog', postdetail).then(res => {
dispatch({
type: 'ADD_DATA',
payload: res.data
})
}).catch(error => {
console.log(error)
})
}
I am getting the error:
Cannot read property 'file' of undefined

1. Probably you didn't register middleware.
According to the doc example, you should register express-fileupload middleware before you refer req.files:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
// default options
app.use(fileUpload());
Also don't forget to add null check in case when no files are uploaded:
app.post('/upload', function(req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
let file = req.files.file;
// do something with uploaded temp file
}
2. Content type should be multipart/form-data when you upload file
const handleSubmit=(e)=>{
e.preventDefault()
const formData=new FormData()
formData.append('file', file)
setfile('')
}
function addPost(postdetail){
axios.post('http://localhost:4000/blog',formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res=>{
dispatch({
type:'ADD_DATA',
payload:res.data
})
}).catch(error=>{
console.log(error)
})
}
3. Other form fields(des, title) may not be submitted using multipart/formdata
Consider open two routes for blog creation.
[POST] '/blog/upload-image' for image upload
[POST] '/blog/new for create blog (title, des and image_id acquired from image upload response)

Related

MulterError: Unexpected field error while uploading image from React js

All the answers related this error is directing towards checking the name upload.single("image") and the name attribute of the file input in client side, which is in my case same as "image" as multer. But still it is giving the error.
Following is the node js code:
const Imagestorage = multer.memoryStorage()
const upload = multer({ storage: Imagestorage })
app.post("/newpost", upload.single("image"), async(req, res) => {
console.log(req.body);
console.log(req.file);
let data={}
// convert base64 image data to string using datauri/parser, upload to cloudinary and send response
const extName = path.extname(req.file.originalname).toString();
const file64 = parser.format(extName, req.file.buffer);
const filename=file64.content
cloudinary.uploader.upload(filename, async(error, result) => {
if (error) {
res.status(500).send("error in uploading file to cloudinary"+error);
} else {
// result.secure_url is the URL of the uploaded file on Cloudinary
console.log(result.secure_url);
let Imageurl=await result.secure_url
data={
name: req.body.name,
location:req.body.location,
likes:req.body.likes,
description:req.body.description,
image:Imageurl
}
console.log(data)
let postedData=await postsModel.create(data)
res.json({
status:"ok",
postedData
})
}
});
});
//error field in case something happens with multer
// app.use((error, req, res, next) => {
// console.log('This is the rejected field ->', error.field);
// });
app.get("*", (req, res) => {
res.status(404).send("PAGE IS NOT FOUND");
})
Frontend code-
import axios from "axios";
import { useNavigate } from "react-router-dom";
const Form = () => {
const navigate = useNavigate();
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
// Append the file input to the form data
const imageFile = formData.get("image");
formData.append("image", imageFile);
// Use Axios to send a POST request to your server with the form data
axios
.post("https://instabackend-gcwk.onrender.com/newpost", formData, {
//.post("http://127.0.0.1:5000/newpost", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
})
.finally(navigate("/insta"));
}
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="image">Image:</label>
<input type="file" id="image" name="image" accept="image/*" />
<button type="submit">Submit</button>
</form>
<button onClick={() => navigate(-1)}>Go Back Home</button>
</div>
);
};
export default Form;
When i tried -
app.use((error, req, res, next) => {
console.log('This is the rejected field ->', error.field);
});
it's giving error field as "This is the rejected field -> image "
Note: There is no issue in fetching the data
Replacing append with set of FormData() is making the code work. Javascript.info explains the working of formData() here
import axios from "axios";
const App = () => {
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
//get image
const imageFile = formData.get("image");
//set image
formData.set("image", imageFile);
axios
.post("https://instabackend-gcwk.onrender.com/newpost", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});
}
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="image">Image:</label>
<input type="file" id="image" name="image" accept="image/*" />
<button type="submit">Submit</button>
</form>
</div>
);
};
export default App;

Why multer is not uploading my image in the public folder?

I am creating one feature to upload images using multer . But i am not able to do so . A link is being created in the prescription but the image is not being saved in the public/images folder .
This is the jsx code.
<p>Upload Prescription</p>
{selectedImage && (
<div>
<img alt="not found" width={"250px"} src={URL.createObjectURL(selectedImage)} />
<br/>
</div>
)}
<br />
<br />
<input
type="file"
name="image"
onChange={(event) => {
console.log('hi');
console.log(event.target.files[0]);
setSelectedImage(event.target.files[0]);
}}
/>
<button onClick={(e)=>{setSelectedImage(null)}}>
Remove
</button>
</div>
</div>
<button onClick={handleClick}>
Add Record
</button>
This is the handleClick function
const handleClick = async (e) =>{
e.preventDefault();
console.log(URL.createObjectURL(selectedImage));
const recordData =
{
diseasename,weight,height,medicines,desc,checkdate,patientId, prescription:URL.createObjectURL(selectedImage)
}
try{
const res = await axios({
method: "POST",
url: "http://localhost:3000/api/record/createrecord",
data: recordData,
withCredentials: false
});
console.log(res.data);
}
catch(err){
console.log(err);
}
}
In controllers, I am setting prescription as req.file
import historyCard from "../models/historyCard.js";
export const medicalHistory = async(req,res,next) =>{
console.log(req.file);
try{
// console.log(req.body);
const newRecord = new historyCard({
"diseasename":req.body.diseasename,
"checkdate":req.body.checkdate,
"weight":req.body.weight,
"height":req.body.height,
"desc":req.body.desc,
"prescription":req.prescription
})
console.log(newRecord);
await newRecord.save();
res.status(200).send(newRecord);
}catch(err){
next(err);
}
}
This is how i have imported multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./public/images");
},
filename: (req, file, cb) => {
cb(
null,
Date.now()+file.originalname
);
},
});
const upload=multer({
storage:storage,
limits:{
fieldSize:1024*1024*3
}
})
const router = express.Router();
router.post('/addrecord',upload.single('image'),medicalHistory);
In database I am storing prescription as
prescription:{
type:String,
default: ""
}
But the thing that is happening is , it is not being in my public folder.
well, you're not sending the file.
You need to use FormData to send the file, and by using its .append method, not an object, with URL.createObject
You can append the file separately, as well as recordData object by stringifying it, and then parse it on the server.
Since the file is stored in a public folder, you can store path to the file as a value of prescription property.
You can then add that property to the parsed recordData object on the server once the file is uploaded (and because only there can you know the file path, because of the custom filename), and then save the whole object:
try this:
on the client upload:
const handleClick = async (e) =>{
e.preventDefault();
console.log(selectedImage.name);
// add data, without prescription
const recordData =
{
diseasename,weight,height,medicines,desc,checkdate,patientId
}
// use FormData
const formData = new FormData();
// append JSON data
formData.append('recordData', JSON.stringify(recordData));
// append file. the name should match the one on multer: upload.single('image'),
formData.append('image', selectedImage);
try{
const res = await axios({
method: "POST",
url: "http://localhost:3000/api/record/createrecord",
data: formData, // send formdata
withCredentials: false
});
console.log(res.data);
}
catch(err){
console.log(err);
}
}
and on the controller parse recordData, and add file path as prescription's property value:
const recordData = JSON.parse(req.body.recordData);
// save only path to the file, since it's in the public folder
recordData.prescription = req.file.path;
console.log('recordData', recordData);
// save..
const newRecord = new historyCard(recordData);

Node / React : I can't upload an image with my post with multer

I'm trying to create a small social network in which we can send posts (with or without images).
I manage to create posts without an image (just text), it works very well, but as soon as I add an image to my form and submit the form, it is impossible to find the image. Normally it should be saved in the "images" folder but it is always empty.
I am using multer to do that, here is my code :
My form component :
const WhatsUpForm = ({ className, id, name, placeholder }) => {
const [inputValue, setInputValue] = useState("");
const inputHandler = (e) => {
setInputValue(e.target.value);
};
const submitHandler = async (e) => {
e.preventDefault();
const post = {
author_firstname: JSON.parse(localStorage.getItem("user")).user_firstname,
author_lastname: JSON.parse(localStorage.getItem("user")).user_lastname,
message: inputValue,
date_creation: dayjs().format(),
image_url: ""
};
// POST request
await POST(ENDPOINTS.CREATE_POST, post);
// document.location.reload()
};
return (
<form className={className} onSubmit={submitHandler} method="POST" action="/api/post" enctype="multipart/form-data">
<input className="testt" type="text" id={id} name={name} placeholder={placeholder} required value={inputValue} onChange={inputHandler}/>
<div className="icons_container">
<input type="file" name="image" id="image" className="icons_container__add_file" />
<label for="image">
<FontAwesomeIcon icon={faImages} />
</label>
<button type="submit" className="icons_container__submit">
<FontAwesomeIcon icon={faPaperPlane} />
</button>
</div>
</form>
);
};
My routes and the multer's code :
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "../images");
},
filename: (req, file, callback) => {
console.log("multer");
console.log("file :", file);
callback(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer({ storage: storage });
// Post CRUD
router.get("/", auth, postCtrl.getAllPosts);
router.post("/", auth, upload.single("image"), postCtrl.createPost);
router.delete("/:id", auth, postCtrl.deletePost);
router.put("/:id", auth, postCtrl.updatePost);
console.log("multer") is not trigger, and when i look the payload in network tab in my browser, i don't see any images.
And finally, my controller for createPost function :
exports.createPost = (req, res, next) => {
let { body } = req;
delete(req.body.image_url)
body = {
...body,
likes: "",
};
const sql = "INSERT INTO posts SET ?";
db.query(sql, body, (err, result) => {
if (err) {
res.status(404).json({ err });
throw err;
}
res.status(200).json({ msg: "Post added..." });
});
};
For now, i don't want to put the image's URL in my SQL DB, i just want to save the image in my images folders. I have verified the path (../images) and it's coorect.
How do I save the image in my image folder?
I don't see the file data gets sent to server from your POST request.
// object post doesn't have the file data
await POST(ENDPOINTS.CREATE_POST, post);
Consider using FormData
const submitHandler = async (e) => {
e.preventDefault();
const post = new FormData();
// non form data
formData.append("author_firstname", JSON.parse(localStorage.getItem("user")).user_firstname);
...
// form data
formData.append("image", document.getElementById("image").files[0]);
...
// POST request
await POST(ENDPOINTS.CREATE_POST, post);
// document.location.reload()
};

why my req.files always null while req.body have the file :upload file with express-fileupload/reactjs

i need ur help i can't find the mistake :
I m trying to upload a file in my code using express-fileupload but in nodemon the req.files are always null: files: null but I find that my file attribute pass to req.body like : body: { file: '[object File]' }
i try testing my URL with RESTer and it's work the file upload but didn t work with my react input i try all the last 4days lot of things but i still didn t find where is my mistake is it in formData?? plaise help me
there is my code for frontend react:
import Message from './Message';
import Progress from './Progress';
import axios from 'axios';
const FileUpload = () => {
const [file, setFile] = useState('');
const [filename, setFilename] = useState('Choose File');
const onChange = e => {
console.log(e.target.files[0].name)
setFile([e.target.files[0]]);
setFilename(e.target.files[0].name);
};
const onSubmit = async e => {
const formData = new FormData();
formData.append("file", file);
if(!formData){
console.log("empty");}
try {
const res = await axios.post('http://localhost:5001/up', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log("file read");
console.log(res)
const { fileName, filePath } = res.data;
} catch (err) {
console.log(err)
}
};
return (
<Fragment>
<form onSubmit={onSubmit} enctype='multipart/form-data'>
<div className='custom-file mb-4'>
<input
type='file'
enctype='multipart/form-data'
className='custom-file-input'
id='customFile'
onChange={onChange}
/>
<label className='custom-file-label' htmlFor='customFile'>
{filename}
</label>
</div>
<input
type='submit'
value='Upload'
className='btn btn-primary btn-block mt-4'
/>
</form>
</Fragment>
);
};
export default FileUpload;
and there is the backend :
import cors from "cors"
import nez_topographie from "./api/controllers/nez_topographie.route.js"
import fileUpload from "express-fileupload"
import multer from "multer"
import bodyParser from "body-parser"
import morgan from "morgan"
const app = express()
app.use(fileUpload({
createParentPath: true
}))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan("dev"))
app.use("/nez_topographie", nez_topographie)
app.post('/up', async (req, res) => {
try {
console.log(req)
if(!req.files) {
console.log("no")
res.send({
status: false,
message: 'No file uploaded'
});
} else {
//Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
let avatar = req.files.file;
//Use the mv() method to place the file in upload directory (i.e. "uploads")
avatar.mv('./' + avatar.name);
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
});
}
} catch (err) {
console.log(err)
res.status(500).send(err);
}
});
export default app
I just ran into this same issue. I had to add a filename to my FormData instance on the front end.
const formData = new FormData();
formData.append("file", file, "myfile.txt");
If you want you can also pass the original file name like so
formData.append("file", file, file.name);

How to upload multiple file with react/node and multer

I'm trying to upload multiple files with React/express and multer. But can't find what's wrong in my code...(I tried many solutions that I found here but I can't see where I'm wrong).
Here is my code :
**Front : **
function App() {
const [file, setFile] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
let newArr = [];
for (let i = 0; i < file.length; i++) {
newArr.push(file[i]);
}
formData.append('monfichier', newArr);
console.log(formData.get('monfichier'));
axios
.post('http://localhost:3000/uploaddufichier', formData)
.then((res) => res.data);
};
return (
<div className='App'>
<form
onSubmit={handleSubmit}
method='POST'
encType='multipart/form-data'
action='uploaddufichier'
>
<input
type='file'
name='monfichier'
onChange={(e) => setFile(e.target.files)}
multiple
/>
<button> envoyer </button>
</form>
</div>
enter code here
BACK
const multer = require('multer');
const fs = require('fs');
const cors = require('cors');
const path = require('path');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'file-storage');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
},
});
const upload = multer({ storage: storage });
app.use(express.json());
app.use(router);
app.use(cors());
app.use('/file-storage', express.static('file-storage'));
app.use(function (err, req, res, next) {
console.log('This is the invalid field ->', err.field);
next(err);
});
app.post(
'/uploaddufichier',
upload.array('monfichier'),
function (req, res, next) {
console.log(req.files);
fs.rename(
req.files.path,
'file-storage/' + req.files.originalname,
function (err) {
if (err) {
res.send('problème durant le déplacement');
} else {
res.send('Fichier uploadé avec succès');
}
}
);
}
);
For now the back-end console.log(req.files) return an empty array...
And the front-end console.log(formData.get('monfichier') return [object File], [object File]
IF anyone could help me for that issue....It'll be glad :)
A small tweak would have fixed it let me fix it and highlight the tweak that will fix it below.
function App() {
const [file, setFile] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
let newArr = [];
//********* HERE IS THE CHANGE ***********
for (let i = 0; i < file.length; i++) {
formData.append('monfichier', file[i]);
}
console.log(formData.get('monfichier'));
axios
.post('http://localhost:3000/uploaddufichier', formData)
.then((res) => res.data);
};
return (
<div className='App'>
<form
onSubmit={handleSubmit}
method='POST'
encType='multipart/form-data'
action='uploaddufichier'
>
<input
type='file'
name='monfichier'
onChange={(e) => setFile(e.target.files)}
multiple
/>
<button> envoyer </button>
</form>
</div>
The array method on multer accepts multiple files over the wire provided they have the corresponding name you specified (in our case 'monfichier'). So what we have done with the for-loop on the front-end is append several files with the same name - monfichier.
This question has been unanswered for 9months but hopefully, it will be helpful to you or anyother person that is facing this blocker.
#cheers
I know this is an old question, however, this solution will be useful to anyone who is experiencing a similar challenge.
The solution is simple. You must attach your photos with the same name on the frontend. then sending them to the backend. The rest will be handled by Multer, and you can access your files via 'req.files'.
Example
React
const formData = new FormData();
for (let i = 0; i < event.target.files.length; i++) {
formData.append("images", event.target.files[i]);
}
fetch("http://localhost:3003/api/v1/upload", {
method: "POST",
body: formData,
});
};
Backend - ExpressJs + Multer
gallaryRouter
.route("/:galleryId")
.post(
UploadGallery.array("images"),
(req,res)=>{console.log(req.files)}
)

Resources