无法在Angular应用上正确获取GridFS图像

时间:2019-10-09 22:19:22

标签: node.js angular mongodb mongoose

我真的是Angular,MongoDB的新手,所以我正在寻求您的帮助! 我正在尝试在Angular应用上显示图像 图像使用Gridfs保存并通过fs.createReadStream

发送到应用程序
//The model
const ProfilePic = mongoose.Schema(
    {
        _id : mongoose.Schema.Types.ObjectId,
        lenght: Number,
        chunksize: Number,
        uploadDate: Date,
        filename: String,
        md5: String,
        contentType: String
    }
);

// Create storage engine
const storage = new GridFsStorage({
  url: mongoURI,

  file: (req, file) => {
    return new Promise((resolve, reject) => {
      const filename = file.originalname;
      const fileInfo = {
        filename: filename,
        bucketName: "ProfilePic"
      };
      resolve(fileInfo);
    });
  }
});

const upload = multer({ storage });

router.post("/setProfilePic", upload.single("picture"), (req, res) => {
  console.log("image received");
  return res.status(200).json({err: "no"})
});


router.get('/getProfilePic/:filename', (req, res) => {
  gfs.collection('ProfilePic'); //set collection name to lookup into

  /** First check if file exists */
  gfs.files.find({filename: req.params.filename}).toArray(function(err, files){
      if(!files || files.length === 0){
          return res.status(404).json({
              responseCode: 1,
              responseMessage: "error"
          });
      }
      // create read stream
      var readstream = gfs.createReadStream({
          filename: files[0].filename,
          root: "ProfilePic"
      });
      // set the proper content type 
      res.set('Content-Type', files[0].contentType)
      // Return response
      return readstream.pipe(res);
  });
});

// method used to fetch the image
async getProfilePic(name) {
    return this.http.get(this.url + "user/getProfilePic/" + name);
  }

这是我在应用程序上遇到的错误: 意外令牌-JSON中位置0

我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

客户端/浏览器正尝试将响应解析为json,因为这是默认设置。只需传递一个responseType属性设置为'blob'的对象,它就可以工作。

// method used to fetch the image
async getProfilePic(name) {
    return this.http.get(this.url + "user/getProfilePic/" + name, {responseType: 'blob'});
}

https://angular.io/api/common/http/HttpRequest#responseType