node.js – 捕获String并将其存储在mongoDB中

我正在尝试捕获用户上传图像时文本生成的字符串(基于客户端/会话).

执行db.collection.find()时的输出;从上传时控制台上传时间:

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

在这里,我想要“imagelocation”:“N / A”也.

该字符串基于上载图像时的用户位置.
我想将特定的字符串值连接到上面显示的图像对象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',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.originalname);
 },imagelocation: function(req,cb){
   cb(null,$('#coordinates').innerHTML);
 }
});

var upload = multer({
 storage: storage
});

router.get('/',res,next) {
 res.render('layouts/main.handlebars');
});

router.post('/',upload.any(),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 – 我将如何捕获字符串并将其与图像一起发送到我的MongoDB?

整个项目可在以下位置找到:https://github.com/joelfolkesson/myapp

要签入的文件

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

解决方法

要使用您的图像文件发送一个长字符串,您只需在提交时将其与表单一起发送.例如,在隐藏的输入字段中.

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

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

app.post('/api/file',res){
    var upload = multer({
        storage: storage
    }).single('imageFile')
    upload(req,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('/',res){
    res.render('index');
})

var storage = multer.diskStorage({
    destination: function(req,callback){
        callback(null,'./uploads');
    },file.fieldname + '-' + Date.Now() + path.extname(file.originalname));
    }
})

app.post('/',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的终端运行它时,此代码有效.提交表单后,文本字段的内容将打印到控制台.

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...