无法使用express-fileupload上传文件

时间:2018-09-02 12:23:20

标签: node.js express post file-upload axios

我正在使用express-fileupload模块解析上传的文件。 上传是通过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

服务器端代码如下:

router.use(fileUpload());

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

当我尝试上传时,我当然会收到“未上传文件”的信息。

2 个答案:

答案 0 :(得分:0)

您可以选择使用multer处理多部分/表单数据。 您可以按以下方式获取上传的文件

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
  }
});

答案 1 :(得分:0)

最后一步调试后发现data.gameCover是一个数组 所以这就是解决方案

formData.append("file", data.gameCover[0]);