Search code examples
node.jsreactjsmulter

Error: ENOENT: no such file or directory React Node.js


I have an attachment upload feature where I saved the attachment in my public/images folder from client side. Here are my front-end and back-end codes:

function AddAttachment() {

    const history = useHistory();

    const {userId, setUserId} = useContext(UserContext);

    const link = window.location.pathname;
    const split = link.split("/");
    const projectId = split[4];

    const [file, setFile] = useState();
      const [fileName, setFileName] = useState("");
 
      const saveFile = (e) => {
        setFile(e.target.files[0]);
        setFileName(e.target.files[0].name);
      };
 
      const uploadFile = async (e) => {

        e.preventDefault();

        const formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", fileName);
        try {
          const res = await Axios.post(
            "http://localhost:3001/uplatt",
            formData,
            projectId,
          ).then((response) => {
            if(response){
                window.alert('You have successfully uploaded an image!');
                    history.push(`/${userId}/viewproject/${projectId}`);
            }
          });

        } catch (ex) {
          console.log(ex);
        }
      };

  return (
    <div className="d-flex justify-content-center">
            <Card style={{ width: '70%' }}>
            <input type="file" name="file" onChange={saveFile} />
            <button onClick={uploadFile}>Upload</button>
            </Card>
        </div>
  )
}
app.use(express.static("./public"));

var storage = multer.diskStorage({
    destination: (req, file, callBack) => {
        callBack(null, './public/images/')
    },
    filename: (req,file,callBack) => {
        callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

var upload = multer({
    storage: storage
});

app.post("/uplatt", upload.single('file'), (req,res) => {

    if(!req.file){
        console.log("No file upload");
    }
    else{
        console.log(req.file.filename)
        var imgsrc = 'http://127.0.0.1:3000/images/' + req.file.filename;
        var projectId = req.body.projectId;
        var insertData = "INSERT INTO project_attachment(project_attachment_url, project_id) VALUES (?, ?)"
        db.query(insertData, [imgsrc, projectId], (err, result) => {
            if (err){
                throw err
            } 
            else{
                console.log("file uploaded")
                res.send(result);
            }
        })
    }
})

The error was Error: ENOENT: no such file or directory, open 'C:\Users\User\myapp\server\public\images\file-1656055704764.pdf'. I am fully aware that that the path is wrong, since it is supposed to be client instead of server. How do I fix the code to make it recognize client instead of server? I have tried putting ./client/public but it becomes C:\Users\User\myapp\server\client\public\images\file-1656055704764.pdf' instead.


Solution

  • Nevermind, I got the solution. I changed this line:

    destination: (req, file, callBack) => {
       callBack(null, './public/images/')
    },
    

    to

    destination: (req, file, callBack) => {
       callBack(null, './../client/public/images/')
    },