捕获String并将其存储在mongoDB中

我试图捕获一个文本生成的string(基于客户端/会话),当用户正在上传图像。

输出时做db.collection.find(); 从控制台现在上传时:

"_id" : ObjectId("590c67f472667e031fe80a9d"), "path" : "uploads/bicycle.jpg", "originalname" : "bicycle.jpg", "__v" : 0

在这里我想要有"imagelocation" : "N/A"也。

上传图片时,string基于用户的位置。 我想将特定的string值连接到上面显示的图像对象ID。

App.js:

 /image UPLOAD TO MONGODB var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var path = require('path'); app.use(bodyParser.json()); //To get the access for the functions defined in imagefile.js class var routes = require('./imagefile'); // connect to mongo, mongoose.connect('mongodb://localhost:27017/gps'); app.use('/', routes); // To get all the images/files stored in MongoDB app.get('/images', function(req, res) { routes.getImages(function(err, genres) { if (err) { throw err; } res.json(genres); }); }); app.get('/images/:id', function(req, res) { routes.getImageById(req.params.id, function(err, genres) { if (err) { throw err; } res.send(genres.path) }); }); 

path和originalname在我的imagefile.js中声明如下:

 var imageSchema = mongoose.Schema({ path: { type: String, required: true, trim: true }, originalname: { type: String, required: true }, imagelocation:{ // format for storing type: String, required: true } }); module.exports = mongoose.model('Image', stringClass); var Image = module.exports = mongoose.model('files', stringClass); router.getImages = function(callback, limit) { Image.find(callback).limit(limit); } router.getImageById = function(id, callback) { Image.findById(id, callback); } router.addImage = function(image, callback) { Image.create(image, callback); } //multer var storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads/') }, filename: function(req, file, cb) { cb(null, file.originalname); }, imagelocation: function(req,file,cb){ cb(null, $('#coordinates').innerHTML); } }); var upload = multer({ storage: storage }); router.get('/', function(req, res, next) { res.render('layouts/main.handlebars'); }); router.post('/', upload.any(), function(req, res, next) { res.send(req.files); var path = req.files[0].path; var imageName = req.files[0].originalname; var imagepath = {}; imagepath['path'] = path; imagepath['originalname'] = imageName; router.addImage(imagepath, function(err) { }); }); module.exports = router; 

HTML:

 <p id="coordinates">String is generated here</p> 

TL; DR – 如何捕获一个string,并将其上传到我的MongoDB时,与图像一起发送?

整个项目可以在https://github.com/joelfolkesson/myappfind

要检入的文件:

  • imagefile.js

  • app.js //(第204行 – >)

要发送一个与您的图像文件很长的string,你只需发送它与表单提交。 例如在一个隐藏的input字段。

然后,在提交时,您可以将其作为req.body对象的一部分进行访问

下面是一个例子(来自一个API,但你明白了):

 app.post('/api/file', function(req, res){ var upload = multer({ storage: storage }).single('imageFile') upload(req, res, function(err){ if(err){ // handle any errors here ... } console.log(req.body)// <-- here you can access your text string as 'req.body.yourStringIdentifier' res.json({success: true, msg: 'File uploaded'}); }) }) 

如果你有任何问题随时问 :)


编辑:完整的例子

server.js:

 const express = require('express'); const multer = require('multer'); const path = require('path'); const ejs = require('ejs'); var app = express(); app.set('view engine','ejs'); app.get('/', function(req, res){ res.render('index'); }) var storage = multer.diskStorage({ destination: function(req, file, callback){ callback(null, './uploads'); }, filename: function(req, file, callback){ callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } }) app.post('/', function(req, res){ var upload = multer({ storage: storage }).single('imageFile') upload(req, res, function(err){ console.log(req.body.textInput); res.end('File is uploaded'); }) }) var port = process.env.PORT || 7850 app.listen(port, function(){ console.log('Listening on port ' + port); }) 

index.ejs:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>INDEX</title> </head> <body> <form id="uploadForm" enctype="multipart/form-data" method="post"> <input type="file" name="imageFile"> <input type="text" name="textInput"> <input type="submit" value="Upload file" name="submit"> </form> </body> </html> 

当我使用nodemon server.js从terminal运行它时,此代码有效。 提交表单时,文本字段的内容将打印到控制台。

Joel,根据Multer文档,磁盘存储var storage = multer.diskStorage({.....})引擎可以完全控制将文件存储到磁盘,并且只有两个选项可用,即目标和文件名。 它们都是决定文件存储位置的函数。

  • 目的地用于确定上传的文件应存储在哪个文件夹中
  • 文件名用于确定该文件夹内应该命名的文件。

因此,您定义multer.diskStorage的方式是错误的。

如果您尝试将其上传到MongoDB,请参阅以下链接: https : //ciphertrick.com/2017/02/28/file-upload-with-nodejs-and-gridfs-mongodb/

如果要将文件存储在磁盘存储中,然后上载有关使用您的模式存储的文件的一些信息

 var imageSchema = mongoose.Schema({ path: { type: String, required: true, trim: true }, originalname: { type: String, required: true }, imagelocation:{ // format for storing type: String, required: true } }); 

然后进行更改

  var imagepath = {}; imagepath['path'] = path; imagepath['originalname'] = imageName; /* provide logic here as mentioned by David Stenstrøm to read it from request.body and move it to the image schema object router.addImage(imagepath, function(err) { }); 

希望我澄清你的查询:) 🙂