在MEAN中按ID显示图像

时间:2018-07-06 11:39:24

标签: node.js angular mongodb express mean

我正在尝试将图像存储在mongoDB中,并将其取回以从Angular一侧显示。

profile.html

<input class="file-hide" type="file" (change)="fileChangeEvent($event)" 
 placeholder="Upload file..." />
 <button type="button" (click)="upload()">Upload</button> 

profile.component.ts

images=[];
    fileChangeEvent(event) {
        this.profileService.uploadAvatar(event); 
       }

      getImage() {
        this.patientService.getImage().subscribe(
          data => this.images = [data],
          error => console.log(error),
        );
      }

profile.service.ts

    uploadAvatar(event){
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
     let file: File = fileList[0];
     let formData:FormData = new FormData();
     formData.append('avatar', file, file.name);
     let headers = new Headers();
     /** No need to include Content-Type in Angular 4 */
     // headers.append('Content-Type', 'multipart/form-data');
     // headers.append('Accept', 'application/json');

      this.http.post('/api/images', formData)
         .subscribe(
             data => console.log('success'),
             error => console.log(error)
         )
   }

}
getImage(): Observable<any> {
  return this.http.get(`/api/images/:id`);
}

服务器端

  app.post(/images,(req, res, next) => {
  upload(req, res, function(err) {
  // Create a new image model and fill the properties
  let newImage = new Image();
  newImage.filename = req.file.filename;
  newImage.originalName = req.file.originalname;
  newImage.desc = req.body.desc
  newImage.save(err => {
      if (err) {
          return res.sendStatus(400);
      }
      res.status(201).send({ newImage });
      console.log("uploaded")
  });
})
});

app.get(/images,  (req, res, next) => {
  console.log("Get Image By Id")
  let imgId = req.params.id;

  Image.findById(imgId, (err, image) => {
      if (err) {
          res.sendStatus(400);
      }

      // stream the image back by loading the file
      res.setHeader('Content-Type', 'image/jpeg');

      fs.createReadStream(path.join(UPLOAD_PATH, image.filename)).pipe(res);

  })
});

模型

export interface IImageModel extends mongoose.Document {
    filename: string; 
    originalName: string; 
    desc: string;
    created: Date;
    url : String
  };

  // Actual DB model
export var imageSchema = new mongoose.Schema({
    filename: String,
    originalName: String,
    desc: String,
    url : String,
    created: { type: Date, default: Date.now }
});
 export const Image = mongoose.model<IImageModel>('Image', imageSchema);

现在,我可以从前端上传文件,并将其存储在数据库中。我可以使用邮递员按ID查看图像。但是我想从前端显示图像。我为此感到震惊。任何人都可以帮助我显示存储在mongoDB中的图像。can view image using postman

2 个答案:

答案 0 :(得分:0)

如果要使用id获取图像,则需要先从数据库获取id,然后再从数据库中获取数据。像这样更改您的代码,它将起作用

 uploadAvatar(event){
        let fileList: FileList = event.target.files;
        if(fileList.length > 0) {
         let file: File = fileList[0];
         let formData:FormData = new FormData();
         formData.append('avatar', file, file.name);
         let headers = new Headers();
         /** No need to include Content-Type in Angular 4 */
         // headers.append('Content-Type', 'multipart/form-data');
         // headers.append('Accept', 'application/json');


// Once you post the image you will get the back the id
          this.http.post('/api/images', formData)
             .subscribe((img)
                   this.getImage(img.id);
                 data => console.log('success'),
                 error => console.log(error)
             )
       }

    }

    getImage(id): Observable<any> {
      return this.http.get(`/api/images/:id`,{responseType:'blob'});
    }

答案 1 :(得分:0)

这是错误error message

的屏幕截图