0

I am trying to send a file to my express server to be saved. On the front end, when I call console.log(_("#fileElem2").files[0]), I receive something like this:

enter image description here

Front End:

<input type="file" id="fileElem2">
_("#fileElem2").addEventListener("change", (e) => {
    console.log(_("#fileElem2").files[0])
    fetch('/uploadFile', {
        method: 'POST',
        body: _("#fileElem2").files[0]
    })
})

function _(query) {
    return document.querySelector(query);
}

Backend (server):

const express = require('express')
const app = express()
require('dotenv').config()
const http = require('http')
const port = process.env['port']
const path = require("path")
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const helmet = require("helmet");

app.set('socketio', io);

app.post("/uploadFile", (req, res) => {
  console.log(req.body);
})

app.use(express.static('static'))
app.use(express.json())
app.use(helmet())

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "html/index.html"));
})


server.listen(port, () => {
  console.log(`Server running on ${port}!`)
})

io.on("connection", (socket) => {
  // socketio stuff
})

When the console.log(req.body); runs, I only recieve {} in the console. Am I supposed to be using req.body to recieve the file, or is there some other function?

ghosty
  • 53
  • 6
  • `FormData` on the client-side and Multer on the server are really all you need – Phil Feb 20 '23 at 06:51
  • @Dai What is making it a JSON payload? I put `headers: { 'Content-Type': 'multipart/form-data'}` into the fetch request, but now it is just logging `undefined` – ghosty Feb 20 '23 at 06:53
  • 1
    @ghosty My mistake, I saw your remarks about only seeing `{}` so I jumped to an incorrect concusion from a faulty assumption - my earlier comment is now cheerfully withdrawn :) – Dai Feb 20 '23 at 06:55

0 Answers0