最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin15浏览0评论

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

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

我真的是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

我的代码有什么问题?

回答如下:

客户端/浏览器正在尝试将响应解析为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

发布评论

评论列表(0)

  1. 暂无评论