반응형
Node.js/Express 및 Mongoose를 사용하여 MongoDB에 이미지 저장
현재 저는 angular-file-uppload를 사용하여 이미지 업로드를 처리하고 있으며 서버의 파일 시스템에 이미지를 저장하고 HTML로 참조하기만 하면 됩니다.그러나 블로그 게시물에 대해 정의한 스키마 내의 데이터베이스에 직접 이미지를 저장하려고 합니다.
var blogSchema = new Schema({
title: String,
author: String,
body: String,
likes: { type: Number, default: 0 },
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
date: { type: Date, default: Date.now },
imageURL: String // instead of this
image: // store it directly
});
"imageURL: String" stores the path to the image.
이미지 자체를 저장하는 필드를 만들 수 있도록 만들고 싶습니다.저는 제가 이미 업로드한 것처럼 이미지를 업로드하는 것이 아니라 이미지가 업로드된 후 이미지를 변환하여 Mongo에 이진(또는 다른 형태)으로 저장할 수 있다고 생각했습니다.이것이 가능합니까?
감사합니다!
아래 예제는 mongoose를 사용하여 MongoDB에 이미지를 업로드하는 방법을 보여줍니다.원본 소스에 대한 이 링크 클릭
var express = require('express');
var fs = require('fs');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imgPath = '/path/yourimage.png';
mongoose.connect('localhost', 'testing_storeImg');
var schema = new Schema({
img: { data: Buffer, contentType: String }
});
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
console.error('mongo is open');
A.remove(function (err) {
if (err) throw err;
console.error('removed old docs');
// store an img in binary in mongo
var a = new A;
a.img.data = fs.readFileSync(imgPath);
a.img.contentType = 'image/png';
a.save(function (err, a) {
if (err) throw err;
console.error('saved img to mongo');
// start a demo server
var server = express.createServer();
server.get('/', function (req, res, next) {
A.findById(a, function (err, doc) {
if (err) return next(err);
res.contentType(doc.img.contentType);
res.send(doc.img.data);
});
});
server.on('close', function () {
console.error('dropping db');
mongoose.connection.db.dropDatabase(function () {
console.error('closing db connection');
mongoose.connection.close();
});
});
server.listen(3333, function (err) {
var address = server.address();
console.error('server listening on http://%s:%d', address.address, address.port);
console.error('press CTRL+C to exit');
});
process.on('SIGINT', function () {
server.close();
});
});
});
});
이것은 mongodb에 데이터를 저장하는 코드입니다. data이진수입니다.이 'image/jpg, base64, {{data}}'를 표시할 수 있지만 어떻게 표시할 수 있는지 이해할 수 없습니다.base64data.
file.on('data', function (data) {
buffer += data;
var file = new fileModel({
fileData: data
})
var Busboy = require('busboy');
router.post('/upload', function (req, res) {
var busboy = new Busboy({headers: req.headers});
var base64data = "";
var filetype = "";
var name = "";
var argum = [];
var data2
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
var buffer = "";
filetype = mimetype;
name = filename;
// file.setEncoding('base64');
file.on('data', function (data) {
buffer += data;
var file = new fileModel({
fileData: data
})
//
file.save(function (err, file) {
if (err) {
return next(err)
}
// res.json(201, newData)
// console.log("Save in database" + file.desc)
})
});
file.on('end', function () {
base64data = buffer;
});
});
busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated) {
argum.push(val);
});
busboy.on('finish', function () {
var base64dataa = new Buffer(base64data, 'binary').toString('base64');
res.json(base64dataa)
var jsonBin = {
base64data_: base64data, mime_: filetype, name_: name,
owner_: argum[0], description_: argum[1]
}
// res.json(jsonBin)
var file = new fileModel({
fileData: jsonBin.base64data,
mimeType: jsonBin.mime_,
fileName: jsonBin.name_,
fileOwner: jsonBin.owner_,
desc: jsonBin.description_
})
//
file.save(function (err, file) {
if (err) {
return next(err)
}
// res.json(201, newData)
console.log("Save in database" + file.desc)
})
});
req.pipe(busboy);
});
router.get("/:i", function (req, res) {
var dataGet = {_id: req.params.i}
fileModel.findOne(dataGet).exec(function (err, doc) {
if (err) {
return next(err)
}
var base64dataa = new Buffer(doc.fileData,'binary').toString('base64');
var ress = {
fileData: base64dataa,
mime: doc.mimeType,
name: doc.fileName
}
// res.json(ress)
res.contentType('image/jpeg')
res.send(doc.fileData)
})
})
router.post('/display/', function (req, res) {
var data = {
file: req.body.fileData,
mime: req.body.mime,
name: req.body.name
}
res.json(data)
})
언급URL : https://stackoverflow.com/questions/29780733/store-an-image-in-mongodb-using-node-js-express-and-mongoose
반응형
'programing' 카테고리의 다른 글
| Mongoose는 항상 빈 배열 노드를 반환합니다.제이에스 (0) | 2023.07.08 |
|---|---|
| 다음으로 두 구성 요소 간에 데이터 전송 (0) | 2023.07.08 |
| Java를 Maria에 연결할 수 없습니다.DB (0) | 2023.07.08 |
| GitHub에서 모든 저장소를 한 번에 복제하는 방법은 무엇입니까? (0) | 2023.07.08 |
| Excel에 있는 경우 중위수에 필요한 도움말 (0) | 2023.07.08 |