gpt4 book ai didi

node.js - 如何在快速 route 显示图像

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:07 27 4
gpt4 key购买 nike

我在 mongodb 数据库中存储了一些图像,我希望能够通过访问 localhost:3003/api/image/filename 一次显示其中一张图像。

现在我有两条路由,一条将所有图像显示为 JSON (localhost:3003/api/files),一条使用文件名将单个图像显示为 JSON (localhost:3003/api/files/:filename)。

这是我的图像在 mongodb 集合 fs.files 中的外观

[{
"_id": "5b6a203a54c9ff33fccdd107",
"length": 52673,
"chunkSize": 261120,
"uploadDate": "2018-08-07T22:42:02.908Z",
"filename": "9b0cecbccb287d284f116715799fc4be.jpg",
"md5": "ad4350fc16c7e60054eafa0912620f9b",
"contentType": "image/jpeg"
},
{
"_id": "5b6addc9247c341f5861c02e",
"length": 1674791,
"chunkSize": 261120,
"uploadDate": "2018-08-08T12:10:52.976Z",
"filename": "c2c5015081fba1695429872b6e978772.jpg",
"md5": "d03ae745631580df00bd0e84bbd1ff87",
"contentType": "image/jpeg"
},
{
"_id": "5b6addd1247c341f5861c036",
"length": 20423,
"chunkSize": 261120,
"uploadDate": "2018-08-08T12:10:57.737Z",
"filename": "97a4377b042cacd2fae5a87aab5849e2.jpg",
"md5": "7161cc94b3cd73f6837891b58b80f4dc",
"contentType": "image/jpeg"
}]

我不确定是否应该添加它,但这是 mongo 连接:

MongoClient.connect('mongodb://localhost:27017',{ useNewUrlParser: true }, function(error, client) {
if (error) {
console.error('Failed to connect to the database!');
console.log(error);
} else {
console.log('Successfully connected to the database!');
db = client.db('chattdb');
gfscollection = db.collection('fs.files');
}
});

那么如何创建一个 app.get 路由来返回由文件名指定的图像?

编辑:

上传图片到mongodb:

    const storage = new GridFsStorage({
url: 'mongodb://localhost:27017/chattdb',
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });

app.post('/api/files', upload.single('file'), (req, res) => {
res.json({file: req.file});
});

检索图像:

    app.get('/api/image/:filename', (req, res) => {
gfscollection.findOne({filename: req.params.filename}, (err, image) => {
if (!image || image.length === 0) {
return res.status(404).json({
err: 'No file exist'
});
}
res.set('Content-Type', 'image/jpg');
res.send(image);
});
});

用于从前端上传的React组件:

    class FileUpload extends React.Component{
constructor(props){
super()
this.state = {
File: null
};
this.onFileChange = this.onFileChange.bind(this);
}
onFileChange(event) {
this.setState({ File: event.target.value });
}

fileUpload(){

var fd = new FormData();
fd.append('file', this.refs.file.files[0]);

fetch('http://localhost:3003/api/files', {
method: 'POST',
body: fd
}).then((response) => response.json())
.then((result) => {
console.log(result);
})
}

render(){
return <div className="file-input">
<form ref="uploadForm" className="uploader" encType="multipart/form-data" >
<input ref="file" className="file-input-field" name="file" type="file" onChange={this.onFileChange}></input>
<button className="send-btn" onClick={this.fileUpload.bind(this)}>Upload</button>
</form>
</div>
}

};

最佳答案

您需要使用 res.send() 传递存储在 Mongo 中的 Buffer

例如:

    res.contentType(doc.contentType);
res.send(doc.data);

编辑:

看来您需要使用gridfs-stream来获取文件数据并通过响应管道流式传输。

也许这可以帮助你:

Storing and Retrieving files from MongoDB using MEAN stack and GridFS

关于node.js - 如何在快速 route 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com