我用多个这样的问题构建了考试演示
[{
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' });
}
);
为什么您认为
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);
}