1

I'm using express-fileupload module to parse uploaded file. Upload is done with axios.

const formData = new FormData();
formData.append("file", data.gameCover);
formData.append("gameTitle", data.gameTitle);
formData.append("gamePrice", data.gamePrice);
formData.append("description", data.description);

return axios.post(apiUrl + "/games/add", formData).then(res => {
  dispatch({ type: ADD_GAME, payload: res.data.game });
});

This is the POST request

Serverside code looks like this:

router.use(fileUpload());

router.post("/add", (req, res) => {
  if (!req.files) return res.status(400).send("No files were uploaded.");

Of course I'm getting "No files were uploaded" when trying to upload.

1

3 Answers 3

4

Finally after debugging step after step found that data.gameCover is an array so that's the solution

formData.append("file", data.gameCover[0]);
Sign up to request clarification or add additional context in comments.

Comments

0

You can optionaly use multer for handling multipart/formdata. you can then get the uploaded file as follows

const express = require('express');
const path = require('path');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage(
{destination: (req, file, cb)=>{
    cb(null, path.join(__dirname, '../uploads'));
  },
filename: (req, file, cb)=>{
    cb(null, file.originalname);
  }
});
let upload = multer({storage: storage});

// access the uploaded file with your route handler
router.post('/upload',upload.single('file'), (req, res, next)=> {
  if(req.file){
    //you can access your uploaded file
  }
});

6 Comments

I've already tried this method. Everything done exactly like in your's example and getting req.file undefined
check if you are uploading the file correctly, try using postman and send a post request to your endpoint and attach the file to the body of your request
Yes, and I'm getting response "No file uploaded"
confirm if your express server is running on the specified port.
Yes it does run on specified port
|
0

For anyone that is having the same problem, express-fileupload checks 3 things:

  1. That the "content-type" header has either the string "boundry=" in it, or "multipart", depending on the express-fileupload version that is being used.
  2. That the "content-length" header is not 0.
  3. That the method is not 'GET', 'HEAD', 'DELETE', 'OPTIONS', 'CONNECT' or 'TRACE'.

If one of those validations fails, you get the mentioned error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.