首页 > 解决方案 > 我使用 Node.js 和 GridFS 上传带有图像文件的元数据中的 UserId 和 UserName,我只能在元数据只有 UserID 时检索 Image

问题描述

我使用 Node.js 和 GridFS 上传图像文件并将UserIDUserName保存在元数据中,但是当元数据只有 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 ,表格列表显示所有上传的用户信息。

请帮我解决元数据问题。

标签: node.jsgridfsdatabase-metadata

解决方案


推荐阅读