使用 multer 上传对象数组中的多个文件

问题描述 投票:0回答:1

我用多个这样的问题构建了考试演示

[{
 image: an_image_file,
 audio: audio_file,
 text: just_text,
 another_text: text
}]

问题是我无法使用 multer 处理上传文件,因为图像文件和音频文件位于每个问题的对象数组中。

这是我的前端代码:

const onSubmit = async (data) => {
    const form = new FormData();
    data.questions.forEach((question, index) => {
      form.append(`questions[${index}].img`, question.img);
      form.append(`questions[${index}].audio`, question.audio);
      form.append(`questions[${index}].text`, question.text);
    });
    try {
      const result = await axios.post(
        'http://localhost:1445/api/v1/exam',
        form
      );
      console.log(result);
    } catch (err) {}
  };

如果我使用

upload.any()
它可以工作,但它似乎不利于安全。请让我知道如何处理这个问题。

更新#1: 这是我的后端代码:

const multer = require('multer');
const compression = require('compression');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use('*', cors());
app.use(compression());

const upload = multer({
  limits: 100000000,

  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      console.log(__dirname);
      const dir = path.join(__dirname, '..', 'public');
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
      }
      cb(null, dir);
    },
    filename: (req, file, cb) => {
      console.log('body', req.body);
      cb(null, `${date}_${file.filename}`);
    },
  }),
});

const router = express.Router();
const api = router.post(
  '/exam/',
  upload.any(),
  (req, res, next) => {
    console.log(req.body);
    console.log(req.files);
    return res.json({ ok: 'ok' });
  }
);
node.js express multer
1个回答
0
投票

为什么您认为

upload.any
不利于安全?

这样的事你能别做吗?

const upload = multer({
  ... // current options,
  fileFilter
});

const expectedMimetypes = [...];

function fileFilter(req, file, cb) {
  // write your logic here to determine of the file
  // is of one of the types that you expect
  // You can do that using "file.mimetype"
  const accept = expectedMimetypes.indexOf(file.mimetype) !== -1;
  callback(null, accept); 
}
© www.soinside.com 2019 - 2024. All rights reserved.