我想从浏览器上传图片并将其存储在本地文件中,并在mongodb中添加文件名。 当我想要检索文件时,存储在本地文件夹中的文件应该显示在浏览器中
谢谢你, Babji
答案 0 :(得分:0)
将图像上传到本地文件夹并保存到mongodb的路径,请按照以下代码进行..
app.post('/api/images', multipart(), function(req, res) {
//Create folder to store image as per year and month
console.log(path.resolve(__dirname));
if (! fs.existsSync(path.resolve(__dirname) + "/public/images/" + shortMonth[new Date().getMonth()] + "_" + new Date().getFullYear())) {
fs.mkdir(path.resolve(__dirname) + "/public/images/" + shortMonth[new Date().getMonth()] + "_" + new Date().getFullYear());
}
var tempPath = req.files.file.path;
var ext = path.extname(req.files.file.name).toLowerCase();
var newFileName = '/images/' + shortMonth[new Date().getMonth()] + "_" + new Date().getFullYear() + "/" + genarateUniqueHash() + ext;
console.log('newFileName:', newFileName);
var targetPath = path.resolve('./public' + newFileName);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
fs.rename(tempPath, targetPath, function(err) {
if (err) {
throw err;
}
res.send(200, {
path: newFileName
});
});
} else {
fs.unlink(tempPath, function() {
if (err) {
throw err;
}
res.json(500, {
error: 'Only image files are allowed.'
});
});
}
});
如果您使用angular-js
,请不要忘记使用ng-file-upload