gpt4 book ai didi

javascript - 如何使用 Nodejs 从 mongoDB 检索图像路径

转载 作者:行者123 更新时间:2023-12-03 03:28:03 24 4
gpt4 key购买 nike

我已使用 Busboy 将图像上传到本地目录并通过 使用 Mongoose 到 MongoDB 的图像路径,但现在我无法 检索路径 在我的 ejs View 中显示图像。我是这个nodejs的新手。请帮我 显示图像。

非常感谢您:)

var express = require('express');    //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path'); //used for file path
var fs = require('fs-extra'); //File System - for file manipulation
var mongoose = require('mongoose');
var mongoClient = require('mongodb').mongoClient;
var objectId = require('mongodb').ObjectId;
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/postname');
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4 Route definition
============================================================ */
app.set('view engine','ejs');
app.use(express.static(__dirname + '/public'));

var nameSchema = mongoose.Schema({
newfile: Object,
path: String
});

var compileSchema = mongoose.model('foods', nameSchema);
app.get('/', function(req, res, next) {
res.render('index',{'title': 'New post app'});
});
app.route('/')
.post(function (req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
fstream = fs.createWriteStream(__dirname + '/public/uploads/' + filename);
var dirname = path.join(__dirname + '/public/uploads/' + filename);
file.pipe(fstream);
//mongo save
var paths = new compileSchema({newfile : dirname, passReqToCallback: true});
paths.save(function(err){
if(err) throw err;
compileSchema.find({newfile: dirname}, (err, result) =>{
console.log();
return result;
});
});
fstream.on('close', function () {
console.log("Upload Finished of " + filename);
//where to go next
res.redirect('/profile');
});
});
});
app.get('/profile', (req, res)=>{
res.render('profile',{photo: req.result});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});

我的 Ejs 文件是:

<img src='<%= photo.newfile %>' >

最佳答案

这是典型的从Mongodb写入和读取的过程使用Mongoose 。我还没有检查你的流媒体和其他东西是否工作正常,但数据库工作流程这样会更好。

var express = require('express');    //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path'); //used for file path
var fs = require('fs-extra'); //File System - for file manipulation
var mongoose = require('mongoose');
var mongoClient = require('mongodb').mongoClient;
var objectId = require('mongodb').ObjectId;
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/postname');
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4 Route definition
============================================================ */
app.set('view engine','ejs');
app.use(express.static(__dirname + '/public'));

//You can import your schema like this
const Name = require('./name');

var compileSchema = mongoose.model('foods', nameSchema);
app.get('/', function(req, res, next) {
res.render('index',{'title': 'New post app'});
});

//I have changed your route since it seems to be clashing with the above
app.post('/save' ,function (req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
fstream = fs.createWriteStream(__dirname + '/public/uploads/' + filename);
file.pipe(fstream);
var dirname = path.join(__dirname + '/public/uploads/' + filename);
//mongo save

fstream.on('close', function () {
//You can either save to mongodb after streaming closes or while it is streaming but in this case I will do it after.
console.log("Upload Finished of " + filename);
//where to go next

//Declare your schema object here
let name = new Name({
newfile:'Whatever you want to store here',
path: path
});

//Save your declared schema like this
name.save((err) => {
if(err) throw err;

console.log(`saved : ${name}`);

//When you redirect here, it will go to /profile route
res.redirect('/profile');
});
});
});
});
app.get('/profile', (req, res)=>{

//You must retrieve from mongodb your object here if this is where you want the object to be

//{} empty query will find all objects in the table
Name.find({}, (err, result) => {
if(err) throw err;
//after everything was found, send it to front end

res.render('profile',{
photo: req.result,
//Now your 'compileSchema' object is available at front end as 'result' object
result:result
});
});
});

var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});

name.js(为您将使用的每个表创建一个架构 js 文件)

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let compileSchema = new Schema({
newfile: Object,
path: String
});

let Compile = mongoose.model('Compiles', compileSchema);

module.exports = Compile;

首先检查您是否正确接收和传输文件。如果是的话,它一定工作得很好。另外,我不知道你为什么要保存newfile:object字段,但您真正需要做的就是保存图像文件的路径,然后在需要使用图像的位置检索它,并将路径用作 <img src='path'>请参阅评论。

关于javascript - 如何使用 Nodejs 从 mongoDB 检索图像路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46224306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com