存储图像并从MongoDB调用它们



我在网上看了一下,只得到了几种方法可以在测试代码中工作,但从来没有在我的实际代码上工作过。我正在尝试让用户上传.jpg图像,然后我想稍后调用它以显示。这是我到目前为止得到的。

fs = require("fs");
multer= require("multer");
app.use(multer({ dest: "./uploads/:id",
rename: function (fieldname, filename) {
return filename;
},
}));

然后从我正在使用的表单中提取文件:

image: req.body.image

至于将其放入数据库的代码,我不确定,这是我想出的,但不太确定它是否有效。我也不知道将它放到我已经拥有的更大路线中的哪个位置。

这是小代码:

app.post("/api/photo",function(req,res){
var Startup = new Startup();
Startup.img.data = fs.readFileSync(req.files.userPhoto.path);
Startup.img.contentType = "image/jpg";
Startup.save();
});

这是表单其余部分的工作(图像除外(路由代码。

// CREATE add new startup to database
app.post("/startup-submit", function(req, res) {
// Get data from form
I create the variables here, removed as too much code and code for the image draw is above.    
//Pass data through | Write better explaination later
var newStartup = {about_startup: about_startup, social_media: social_media, about_founder: about_founder};
Startup.create(newStartup, function(err, newlyCreatedStartup){
if(err){
console.log(err);
} else {
// Redirect back to show all page
res.redirect("/startups");
}
});
});

我知道小型和大型代码上的路由路径不对齐,但我使用它进行测试。

如何网格化和修复此代码,以便我能够将图像/文件上传到我的数据库?

那么我该如何称呼它为使用 EJS 的 src。会不会只是">这是我想出的最好的。我敢肯定,这远非正确。

按照文档进行操作。

(1(dest是您存储文件的地方。./uploads/:id看起来不像一个有效的目的地。

(2(你从哪里得到rename选择?

(3(不要将实际图像存储在数据库中。只需存储文件名。

它应该看起来更像

var fs = require("fs"),
multer = require("multer");
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
// here is where you would add any extra logic to create directories
// for where you will upload your file
cb(null, './uploads')
},
filename: function (req, file, cb) {
// here is where you would add any extra logic to rename your file
cb(null, file.fieldname);
}
})
});
app.post("/api/photo", upload.single('fieldname'), function (req, res, next) {
// at this point, the file should have been uploaded
// you can get info about your file in req.file
console.log(req.file);
var startup = new Startup();
startup.img.data = req.file.filename;
startup.img.contentType = req.file.mimetype;
startup.save(function (err) {
if (err) return next(err);
// send response
});
});

你可能会发现 fs-extra 有用,特别是 fs.mkdirs(( 如果你想创建目录,例如/this/path/does/not/exist.

最新更新