Отобразить полученное изображение в HTML из mongodb - PullRequest
1 голос
/ 22 мая 2019

Я хочу отобразить изображение, полученное из mongodb, в HTML.

мои данные консоли:

{originalname: "dhoni.jpg", имя файла: "file-1558517416483.",contentType: "image / jpeg"} contentType: "image / jpeg" имя файла: "file-1558517416483."originalname: "dhoni.jpg" proto : Object

Это выходные данные моей консоли.Я хочу отобразить изображение в своем HTML. Как мне этого добиться.

Как получить изображение и отобразить его на моей html-странице.

//server.js:

let express = require('express'); 
let app = express(); 
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/files');
let conn = mongoose.connection;
let multer = require('multer');
let GridFsStorage = require('multer-gridfs-storage');
let Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
let gfs = Grid(conn.db);
let port = 3000;

// Setting up the root route
app.get('/', (req, res) => {
    res.send('Welcome to the express server');
});

// Allows cross-origin domains to access this API
app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin' , 'http://localhost:4200');
    res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.append("Access-Control-Allow-Headers", "Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
    res.append('Access-Control-Allow-Credentials', true);
    next();
});

// BodyParser middleware
app.use(bodyParser.json());

// Setting up the storage element
let storage = GridFsStorage({
    gfs : gfs,

    filename: (req, file, cb) => {
        let date = Date.now();
        // The way you want to store your file in database
        cb(null, file.fieldname + '-' + date + '.'); 
    },

    // Additional Meta-data that you want to store
    metadata: function(req, file, cb) {
        cb(null, { originalname: file.originalname });
    },
    root: 'ctFiles' // Root collection name
});

// Multer configuration for single file uploads
let upload = multer({
    storage: storage
}).single('file');

// Route for file upload
app.post('/upload', (req, res) => {
    upload(req,res, (err) => {
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }
        res.json({error_code:0, error_desc: null, file_uploaded: true});
    });
});

// Downloading a single file
app.get('/file/:filename', (req, res) => {
    gfs.collection('ctFiles'); //set collection name to lookup into

    /** First check if file exists */
    gfs.files.find({filename: req.params.filename}).toArray(function(err, files){
        console.log("add");

        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: "ctFiles"
        });
        // set the proper content type 
        res.set('Content-Type', files[0].contentType)
        // Return response
        return readstream.pipe(res);
    });

});

// Route for getting all the files
app.get('/files', (req, res) => {
    let filesData;
    let count = 0;
    gfs.collection('ctFiles'); // set the collection to look up into

    gfs.files.find({}).toArray((err, files) => {
        // Error checking
        if(!files || files.length === 0){
            return res.status(404).json({
                responseCode: 1,
                responseMessage: "error"
            });
        }
        // Loop through all the files and fetch the necessary information
        files.forEach((file) => {
            filesData = {
                originalname: file.metadata.originalname,
                filename: file.filename,
                contentType: file.contentType
            }
        });
        res.json(filesData);
    });
});

app.listen(port, (req, res) => {
    console.log("Server started on port: " + port);
});
<!--app.component.html:-->

  <div class="row">
      <div class="col-md-4">
        <br>
          <form>
              <div class="form-group">
                  <label for="multiple">Choose file(s)</label>
                  <input type="file" class="form-control" name="multiple" ng2FileSelect [uploader]="uploader" multiple  />
              </div>            
          </form>
      </div>
      </div>
      <div class="col-md-8">
           File(s) Selected: {{ uploader?.queue?.length }}
          <table class="table">
              <thead>
              <tr>
                  <th width="50%">Name</th>
                  <th>Size</th>
                  <th>Progress</th>
                  <th>Status</th>
                  <th>Actions</th>
              </tr>
              </thead>
              <tbody>
              <tr *ngFor="let item of uploader.queue">
                  <td><strong>{{ item.file.name }}</strong></td>
                  <td nowrap>{{ item.file.size/1024/1024 | number:'.2' }} MB</td>
                  <td>
                      <div class="progress" style="margin-bottom: 0;">
                          <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': item.progress + '%' }"></div>
                      </div>
                  </td>
                  <td class="text-center">
                      <span *ngIf="item.isSuccess"><i class="fa fa-check"></i></span>
                      <span *ngIf="item.isCancel"><i class="fa fa-ban"></i></span>
                      <span *ngIf="item.isError"><i class="fa fa-times"></i></span>
                  </td>
                  <td nowrap>
                      <button type="button" class="btn btn-success btn-xs"
                              (click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
                          <span class="fa fa-upload"></span> Upload
                      </button>
                      <button type="button" class="btn btn-warning btn-xs"
                              (click)="item.cancel()" [disabled]="!item.isUploading">
                          <span class="fa fa-ban"></span> Cancel
                      </button>
                      <button type="button" class="btn btn-danger btn-xs"
                              (click)="item.remove()">
                          <span class="fa fa-trash"></span> Remove
                      </button>
                  </td>
              </tr>
              </tbody>
          </table>
</div>
app.component.ts:

import { FilesService } from './../files.service';
import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private FileService: FilesService) { }
  private files = [];
  private url = 'http://localhost:3000/upload';
  private uploader: FileUploader;

  ngOnInit() {
    this.uploader = new FileUploader({url: this.url});

    this.FileService.showFileNames().subscribe(response => {
      console.log(response.json());
      this.files = response.json();
    });
  }
}
file.service.ts:

import { Injectable } from '@angular/core';
import { Http, Headers, ResponseContentType } from '@angular/http';

@Injectable()
export class FilesService {

  constructor(private http: Http) { }

  showFileNames() {
    return this.http.get('http://127.0.0.1:3000/files');
  }
}
...