2017-05-05 49 views
5

我试图为用户上传图像时捕获文本生成的字符串(基于客户端/会话)。做从控制台db.collection.find();当现在上传时捕获字符串并将其存储在mongoDB中

输出:

"_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) 
}); 
}); 

路径和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 - 怎么会我捕获一个字符串,并将其上传到我的MongoDB时,与图像一起发送?

整个项目可以在这里找到:https://github.com/joelfolkesson/myapp

文件中检查:

  • imagefile.js

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

回答

0

要发送一个字符串与您的图像文件很长,你只需发送它与您的形式o提交。例如在一个隐藏的输入字段中。

然后,在提交,您可以访问它作为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终端运行此代码的工作。提交表单时,文本字段的内容将打印到控制台。

+0

嗯,是的,这是最初的想法,但是当我们尝试记录响应时返回“undefined”。你能否尝试用更全面的答案来实现你所写的内容?谢谢! – Joel

+0

查看更新回答:) –

+0

我已经尝试了一个小时,以使您的解决方案工作,但我根本不能。 :/我看不出这将如何将字符串存储在同一个db对象中。 – Joel

0

乔尔, 按照该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) { 

}); 

希望然后更改我澄清查询:) :)

相关问题