I am learning node.js at the moment and I am creating a little application where I can upload images and display them in a gallery.
我正在学习node.js,我正在创建一个小应用程序,我可以上传图像并在图库中显示它们。
Currently I have a form which uploads the image to the server via POST
目前我有一个表单,通过POST将图像上传到服务器
extends ../layout
block content
.col-sm-6.col-sm-offset-3
h1 control panel
form(action="/upload", method="POST",
enctype="multipart/form- data")
input(type="file", name='image')
input(type="submit", value="Upload Image")
The file is then inserted to a mongodb using mongoose
然后使用mongoose将文件插入mongodb
exports.upload = function (req, res) {
fs.readFile(req.files.image.path, function (err, data) {
var imageName = req.files.image.name;
if(!imageName){
console.log("seems to be an
error this file has not got a name");
res.redirect("/");
res.end();
}else{
var newimage = new Image();
newimage.img.data = fs.readFileSync(req.files.image.path);
newimage.img.name = imageName;
newimage.save(function (err, a) {
if (err){
console.log("There was an error saving the image")
res.redirect("/");
res.end();
}
res.redirect("/gallery");
});
}
});
}
In my gallery controller I query the database for all the images and pass them to front-end.
在我的图库控制器中,我查询数据库中的所有图像并将它们传递给前端。
exports.gallery = function (req, res) {
Image.find({}, function(err, image){
if (err)
res.send(err);
else
res.render("site/gallery", {images: image });
});
}
And then in my gallery I try create a new image tag for each of the images
然后在我的图库中,我尝试为每个图像创建一个新的图像标记
extends ../layout
block content
h1 Gallery
each image in images
img(src='#{image.img.data}')
My problem is that I keep getting a 404 error because the browser cannot find the image. But I have a feeling that I might be going about this the wrong way. I have seen GridFS but I feel that it is not suitable for this app as the amount of images in the gallery will be less than 20 max. Am I going about the right way to do this or should I be storing the images on the server and retrieving them that way?
我的问题是我一直收到404错误,因为浏览器无法找到图像。但我有一种感觉,我可能会以错误的方式解决这个问题。我见过GridFS但我觉得它不适合这个应用程序,因为图库中的图像数量将少于20个。我是否采取正确的方式来实现这一目标,还是应该将图像存储在服务器上并以这种方式检索它们?
1 个解决方案
#1
You would typically upload the images to your server's machine filesystem or to a static assets cloud hosting service like AWS S3, and store only the URLs of the images in your database.
您通常会将图像上传到服务器的机器文件系统或静态资产云托管服务(如AWS S3),并仅将图像的URL存储在数据库中。
You could also use a solution like Cloudinary.
您也可以使用像Cloudinary这样的解决方案。
#1
You would typically upload the images to your server's machine filesystem or to a static assets cloud hosting service like AWS S3, and store only the URLs of the images in your database.
您通常会将图像上传到服务器的机器文件系统或静态资产云托管服务(如AWS S3),并仅将图像的URL存储在数据库中。
You could also use a solution like Cloudinary.
您也可以使用像Cloudinary这样的解决方案。