Radomir Radionov
Radomir Radionov

Reputation: 21

sent file from React to Node and got empty obj

I am getting img data and send this data to the server
console.log shows that data exists

 const [fileData, setFileData] = useState("");
 console.log("fileData:", fileData);
 const getFile = (e: any) => {
 setFileData(e.target.files[0]);
 };

 const uploadFile = (e: any) => {
e.preventDefault();
const data = new FormData();
data.append("file", fileData);
axios({
  method: "POST",
  url: "http://localhost:5000/api/setImage",
  data: data,
  headers: {
    "content-type": "multipart/form-data", // do not forget this
  },
}).then((res) => {
  alert(res.data.message);
});
};

server endpoint

router.post("/setImage", userController.setImage);

async setImage(req, res, next) {
try {
  let uploadFile = req.body;
  console.log(uploadFile);
} catch (e) {
  next(e);
}

}

console.log shows empty object but I'm waiting img data

Upvotes: 0

Views: 21

Answers (1)

ajitspyd
ajitspyd

Reputation: 1294

Try using multer with fs and tempy.

router.post("/setImage", multer({ dest: tempy.file() }).single("file"), async (req, res, next) => {
    if (!req.file) return
    fs.readFile(req.file.path, function (err, filedata) {
        if (!req.file) return
        // Here you should get your expected data in filedata variable
    })
})

Upvotes: 1

Related Questions