Don't upload photos to the server, how to solve this problem? on the page index.ejs
a photo gallery should be generated from the added entries. The entry contains a photo. The entry is added, but the photo doesn't load. project (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 }); }); }); };
You need to pass your upload
var as middleware to your upload route.
Here is a snippet from how I have done it previously:
// 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)
}
When I post my image, I make sure I call it photo
to match the key word I used in my multer middleware:
So I create my form data like so:
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.