我正在一个项目上,我需要上传图像并将其保存到MongoDB。我使用NodeJS作为后端,使用Angular Material作为前端。 我在TypeScript中编写节点和angular。如何上载和保存。我也想知道如何芦苇和展示它们。
答案 0 :(得分:0)
选中Multer
使用示例
store.js
import multer from 'multer';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const path = process.cwd() + '\\uploads';
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, `file-${Date.now()}.${file.originalname.split(/[.]+/).pop()}`);
}
});
export const UploadHandler = multer({
storage: storage,
fileFilter(req, file, callback, acceptFile) {
if (['image/png'].indexOf(file.mimetype) === -1) {
return callback(new Error("This File Is Not Supported"), false);
}
return callback(null, true);
}
});
app.js
import store from './store';
app.post('/upload', store.array('files', 1), function (req, res, next) {
if(req.files && req.files.length > 0) {
// files uploaded successfully
}
});