文件未使用 Multer 在 Express JS 中上传

File not uploading in Express JS using Multer

我正在使用 Express JS 创建 API。现在,我有一个路由器,用于使用 multer.

上传图像

这是我的路由器:

const multer = require('multer');

module.exports = (app) => {
  const DIR = './public/';

  const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, DIR);
    },
    filename: (req, file, cb) => {
      cb(null , file.originalname);
    }
  });

  const upload = multer({ storage: storage });

  // I have also tried this but not working
  // const upload = multer({ dest: 'uploads/' });

  app.post('/upload', upload.single('image'), (req, res, next) => {
    res.status(201).json({
      message: "File uploaded successfully"
    });
  });
}

现在,在我的 reactjs 应用程序中,我使用 axios 调用此路由器,如下所示:

const headers = {
  "Content-Type": "multipart/form-data"
}
const body = new FormData();
body.append('image', this.state.selectedCategoryImage);
axios.post('http://localhost:3000/upload', body, { headers }).then((res) => {
  console.log(res);
}).catch((err) => {
  console.log(err);
});

在上面的代码中,this.state.selectedCategoryImage 是从 html <input> 标签中选择的图像。

现在,当我调用此 api 时,我得到了响应 "file uploaded successfully",但我无法在 public 目录中的任何位置看到我上传的图像。我的图片没有上传。

谁能帮我解决问题?

传递文件对象不是URL

URL.createObjectURL(file) // it return file url that you can use to show file preview

对于上传文件,在 axios API 中发送您从文件输入中获得的实际文件

var file = event.target.files[0]; // return actual file

这样它实际上发送了文件对象。