捕获String并将其存储在mongoDB中

Joe*_*oel 5 mongodb node.js multer

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

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', function(req, res) {
    routes.getImageById(req.params.id, function(err, genres) {
    if (err) {
       throw err;
    }

 res.send(genres.path)
 });
 });
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

HTML:

<p id="coordinates">String is generated here</p>
Run Code Online (Sandbox Code Playgroud)

TL; DR - 我将如何捕获字符串并将其与图像一起发送到我的MongoDB?

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

要签入的文件:

  • imagefile.js

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

Dav*_*røm 0

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

然后,在提交时,您可以将其作为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'});
    })
})
Run Code Online (Sandbox Code Playgroud)

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


编辑:完整示例

服务器.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);
})
Run Code Online (Sandbox Code Playgroud)

索引.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>
Run Code Online (Sandbox Code Playgroud)

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