无法将上传的图像保存到Hapi.js中的数据库

时间:2019-05-02 12:17:33

标签: javascript node.js mongodb async-await hapijs

我想使用hapi.js将上传的照片保存在mongodb中。但是我可以将照片上传到uploads文件夹中,但无法将其保存到数据库中。这是代码:

   server.route({
            method: 'POST',
            path: '/upload',
            config: {
                    payload: {
                        output: "stream",
                        parse: true,
                        allow: "multipart/form-data",
                        maxBytes: 2 * 1000 * 1000
                    }
                },

                  handler: async (req, h) => {

                    const response1 = handleFileUpload(req.payload.image);
                    console.log(response1);
                    return response1;

                  }
         });
const handleFileUpload = file => {
    return new Promise((resolve, reject) => {
      const filename = file.hapi.filename
      const data = file._data

      fs.writeFile(`./uploads/${filename}`, data, err => {
        if (err) {
          reject(err)
        }
        resolve({
          message: 'Upload successfully!',
          imageUrl: `${server.info.uri}/uploads/${filename}`
        })
      })
    })
  }

当它发送响应消息和imageUrl时。我必须将该图像URL保存在数据库上,但我不知道如何从promise返回中访问它。我很新。 这是我的模型架构:

const stuSchema = new Schema({
    image : String,
});

html:

   <form method="post" action="/upload" enctype="multipart/form-data">

            <label for="image">Image Upoahhd</label>
            <input name="image" type="file" required >

            <br><br>
            <input type="submit" value="Login">
        </form>

我不知道如何将req.payload.image的值保存到数据库中。我想在 handler 方法上这样做:

const user = new User (imageUrl);
const sav = user.save();
return h.response(sav)

但是我想在resolver函数上编写它们,但是它接受对象

1 个答案:

答案 0 :(得分:0)

您需要将awaithandleFileUpload函数一起使用,以从Promise对象获取数据,然后在下面可以使用save()函数在数据库内部创建文档

handler: async (req, reply) => {
  try {
    const { imageUrl } = await handleFileUpload(req.payload.image);
    const user = new User ({ image: imageUrl });
    const result = user.save();
    return ({ message: 'Saved Successfully' });
  } catch (err) {
    throw err
  }
}

const handleFileUpload = file => {
  return new Promise((resolve, reject) => {
    const filename = file.hapi.filename;
    const data = file._data;

    return fs.writeFile(`./uploads/${filename}`, data, err => {
      if (err) {
        return reject(err)
      }
      return resolve({
        message: "Upload successfully!",
        imageUrl: `${server.info.uri}/uploads/${filename}`
      })
    })
  })
}