node.js - 我使用 Node.js 和 GridFS 上传带有图像文件的元数据中的 UserId 和 UserName,我只能在元数据只有 UserID 时检索 Image
问题描述
我使用 Node.js 和 GridFS 上传图像文件并将UserID和UserName保存在元数据中,但是当元数据只有 UserID 时,我只能通过 UserID 检索图像文件。如果我将 UserName 和 UserPhone 保存在元数据中,我将得到空表列表并且系统不显示“没有文件存在!” 部分代码如下。
//----------Upload Form-----------
<form action="/upload" method="post" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" name="file" id="file1"
onchange="readSingleFile(this.files)">
<label class="custom-file-label" for="file1" id="file-label">Choose_file</label>
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
<input class="metadata"type="text" name="UserID" value="{{user._id}}">
{{!-- <input class="metadata"type="text" name="UserName" value=" {{user.company_name}}">
<input class="metadata"type="eamil"name="UserPhone" value="{{user.Phone}}"> --}}
</form>
//-----********If do not input UserName and UserPhone code works fine ****----
//--------------------GFS-----------------------------
const mongoURI = process.env.MONGODB_URL;
// connection
const conn = mongoose.createConnection(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let gfs;
conn.once("open", () => {
// init stream
gfs = new mongoose.mongo.GridFSBucket(conn.db, {
bucketName: "uploads",
});
});
//------------------------Create -storage Engine --------------
const storage = new GridFsStorage({
// url: (mongoURI, { useUnifiedTopology: true}),
url: mongoURI,
options: { useNewUrlParser: true, useUnifiedTopology: true },
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 UserID = req.body
const fileInfo = {
filename: filename,
bucketName: "uploads",
metadata: req.body, // only way to upload metadata
};
resolve(fileInfo);
});
});
},
});
const upload = multer({ storage });
//-----------------Retrieve Image file -----------------
router.get("/pdf/:UserId", isLoggedIn, (req, res) => {
const file = gfs
.find({ metadata: { UserID: req.params.UserId } }) // metadata query
.toArray((err, file) => {
// Check if file
if (!file || file.legnth === 0) {
return res.status(404).json({
err: "No file exists",
});
}
// return res.json([file]);
res.render("users/list copy", { list: file });
});
});
//-------use hbs Table List all uploaded files -----------
<table class="table table-striped" id="table">
<thead>
<tr>
<th>Date Issued</th>
<th>File Name</th>
<th>Company</th>
<th>Download</th>
<th>Delete File</th>
</tr>
</thead>
<tbody>
{{#each list}}
<tr>
<td onclick="State()" class="magnifiable">{{this.uploadDate}}</td>
<td class="magnifiable">{{this.filename}}</td>
<td>{{this.metadata.UserName}}</td>
<td>
<a href="/image/{{this.filename}}">Statement View
<i class="fa fa-usd fa-lg" aria-hidden="true" style="color: orange" aria-
hidden="true"></i>
</a>
</td>
<td>
<a href="/file/del/{{this._id}}" onclick="return confirm('Are you sure to
delete this record?');" style="color:red"> Remove
<i class="fa fa-trash fa-lg" style="color:red" aria-hidden="true"> </i>
</a>
</td>
{{/each}}
</tr>
</tbody>
</table>
我的问题在元数据中使用 req.body 可以保存许多项目,但如果在元数据 {} 中使用 UserID 检索图像,我必须从上传表单中消除其他输入字段。只留下一个 UerID 输入字段。然后查询... gfs.find({ metadata: { UserID: req.params.UserId } })... 工作,我可以有一个带有长十六进制 code.jpg 或 pdf 的图像文件名列表。但我需要 UserName 来读取谁是文件所有者。 如果我不使用元数据查询,而是使用 ....gfs.find().toArray(.....) ..并且我可以在上传表单中有其他输入字段,例如 UserName UserPhone ,表格列表显示所有上传的用户信息。
请帮我解决元数据问题。
解决方案
推荐阅读
- graphql - 如何使用 graphql-js 类(无 SDL)扩展现有类型?
- c# - 使用列表视图时 UWP 中的 ToolTipService 崩溃
- python - 使用来自 slim 的预训练模型训练 ssd inception_v3
- javascript - 如何在 javascript 中打印 php 变量并更改 php 的数组格式
- ruby-on-rails - 无法在 Rails 中显示模态内容
- java - 尝试将数据从角度插入到 Spring Boot api 时出现“JSON 解析错误:无法构造实例”错误
- wpf - 将数据网格绑定到组合框 WPF
- pandas - AttributeError:“numpy.ndarray”对象没有属性“iloc”
- ios - 如何在 appdelegate 中获取传递的通知详细信息
- directx - IDXGIFactory 和其他 IDXGIFactory 版本有什么区别?