0

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>
 </>
 );
}
Rupak
  • 529
  • 6
  • 16

1 Answers1

-1

You can't just send image file like string or integer value. It does get transferred like that. It's the only way. You need to write it down to disk.

Erenn
  • 625
  • 6
  • 18
  • Multer has a config that takes a destination on where to [persist files](https://github.com/expressjs/multer#multeropts) - no need for "YOU need to write it down to disk". Btw. you can send images and files as string or integer i.e. as base64 - in the end everything is bits and bytes... as long as client and server agrees on the serialization mechanism. – David Renner Jul 29 '22 at 22:32
  • You may not need to write it down to disk but then "Multer" has to. Someone has to write it down to disk. – Erenn Aug 10 '22 at 14:34
  • Certainly not... as OP states file needs to go to Database as whatever necessary (Base64, Binary etc). You can keep the file in-memory as Buffer and forward it through SQL or noSQL: HTTP -> in-memory (via Base64-string or Buffer etc) -> SQL -> DB. Actually if it is placed on-disk unwanted you need to remove it i.e. for compliance or data-safety-regulations - dont do things if [you-aint-gonna-need-it](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it). – David Renner Aug 10 '22 at 21:33
  • I define RAM as disk in this case but whatever. What I ment was it has to be writen in somewhere. – Erenn Aug 11 '22 at 08:11