I am sending a file from react js as frontEnd. And I am using node js as a backend to get that file. I am using multer to uploading files to my database. But when I console log my file as: "console.log(req.file)" it gives my buffer data as:
{
fieldname: 'files',
originalname: '2.JPG',
encoding: '7bit',
mimetype: 'image/jpeg',
buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 60 00 60 00 00 ff e1 10 ee 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 04 01 3b 00 02 00 00 00 0c 00 00 ... 44740 more bytes>,
size: 44790
}
But I want to get the file, not the buffer data. Can anyone help!
Here is my backend code:
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const app = express()
app.use(express.json());
app.use(cors())
app.post('/post', upload.single('files'), (req, res) => {
console.log(req.file)
})
here is my front
const App = () => {
const [data, setdata] = useState();
const [name, setname] = useState()
const changeHandler = (e) => {
e.preventDefault()
setname(e.target.name)
setdata(e.target.files[0])
}
const submitData = async (e) => {
e.preventDefault()
const imageData = new FormData();
imageData.append('name', name)
imageData.append('files', data);
axios.post('http://localhost:8000/post', imageData)
.then((res) => console.log(res))
.catch((e) => console.log(e))
}
return (
<>
<form onSubmit={submitData} className="app">
<input onChange={changeHandler} name="image" type="file" />
<button type="submit">Submit</button>
</form>
</>
);
}