[英]How to upload a file to the server (Node.js)
不要将照片上传到服务器,该如何解决? 在index.ejs
页面上,应该从添加的条目中生成一个图库。 条目包含一张照片。 该条目已添加,但照片未加载。 项目(GitHub) app / routes.js:
var upload = multer({ storage: storage, limits: {fileSize: 7}, fileFilter: function (req, file, cd) { checkFileType(file, cd); } }).single('filePhoto'); function checkFiletType(file, cd) { const fileTypes = /jpeg|jpg/; const extname = fileTypes.test(path.extname(file.originalname).toLowerCase()); const mimetype = fileTypes.test(file.mimetype); if (extname && mimetype) { return cd(null, true); } else { cd('Error: only JPEG or JPG!') } var Photo = require('../app/models/photo'); module.exports = function (app, passport) { app.get('/', function (req, res,next) { Photo.find({}, function (error, photos) { var photoList = ''; res.render('index.ejs', {photoList: photos}); }); }); } app.post('/addPhoto', function (req, res, next) { next(); }, function (req, res) { var newPhoto = new Photo(req.body); newPhoto.save().then(function (response) { console.log('here', response); res.status(200).json({code: 200, message: 'OK'}); }).catch(function (error) { console.error('new photo error', error); }); },function (req, res) { Photo.find({}, function (error, photos) { res.send('index.ejs', { photoList: photos }); }); }); };
您需要将upload
变量作为中间件传递到上传路径。
这是我以前做过的片段:
// Route:
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
router.post('/upload', upload.single('photo'), ImageController.upload);
// Image Controller:
upload(req, res){
console.log("file", req.file)
}
发布图像时,请确保将其命名为photo
以匹配在multer中间件中使用的关键字:
所以我像这样创建表单数据:
const formData = new FormData()
formData.append('photo', {
uri: data.uri,
type: 'image/jpeg',
});
axios.post(`${SERVER}/images/upload`,
formData: formData,
{ headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => console.log("response", response))
.catch(err => console.log('err', err))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.