从节点服务器流式传输图像数据会导致文件损坏(gridfs-stream)

时间:2018-06-04 17:58:24

标签: node.js mongodb vue.js

我决定在此处(123)和此处(12)进行广泛搜索后发布此内容其他相关职位。我失去了希望,但不会轻易放弃:)

我使用multer将PNG图像上传到mongo数据库:

const storage = new GridFsStorage({
    url: 'mongodb://my_database:thisIsfake@hostName/my_database',
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {     // generating unique names to avoid duplicates
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex') + path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'media',
            metadata : {
              clientId : req.body.client_id  // added metadata to have a reference to the client to whom the image belongs
            }
          };
          resolve(fileInfo);
        });
      });
    }
  });
const upload = multer({storage}).single('image');

然后我创建一个流并将其传递给响应:

loader: function (req, res) {
    var conn = mongoose.createConnection('mongodb://my_database:thisIsfake@hostName/my_database');
    conn.once('open', function () {
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('media'); 
    gfs.files.find({ metadata : {clientId : req.body.id}}).toArray(
    (err, files) => {
        if (err) throw err;
        if (files) {
            const readStream = gfs.createReadStream(files[0].filename);  //testing only with the first file in the array
            console.log(readStream); 
            res.set('Content-Type', files[0].contentType)
            readStream.pipe(res);    
        }  
    });  
    });
}

Postman对终点的POST请求导致响应正文显示为图像文件:

enter image description here

在前端,我在File对象中传递响应,读取它并将结果保存在img的src属性中:

findAfile(){
            let Data = {
                id: this.$store.state.StorePatient._id,         
            };
            console.log(this.$store.state.StorePatient._id);
            visitAxios.post('http://localhost:3000/client/visits/findfile', Data )
            .then(res => {
                const reader =  new FileReader();
                let file = new File([res.data],"image.png", {type: "image/png"});
                console.log('this is file: ',file);
                reader.readAsDataURL(file);  // encode a string  
                reader.onload = function() {
                    const img = new Image();
                    img.src = reader.result;
                    document.getElementById('imgContainer').appendChild(img);
                };
            })
            .catch( err => console.error(err));

        }

我的File对象类似于使用输入字段时更大的文件对象: enter image description here

这是原始文件: enter image description here

检查元素时,我看到: enter image description here

看起来数据URI应该在哪里,但它与文件输入上的原始图像不同: enter image description here

同样,当我想通过输入元素显示它时:

onFileSelected(event){
        this.file = event.target.files[0];
        this.fileName = event.target.files[0].name;
        const reader =  new FileReader();
        console.log(this.file);
        reader.onload = function() {
             const img = new Image();
             img.src = reader.result;
             document.getElementById('imageContainer').appendChild(img);
        };
        reader.readAsDataURL(this.file);   
}

我明白了:

enter image description here

但是当从响应中读取它时,它已被破坏:

enter image description here

Postman说得对,所以我的前端代码一定有问题,对吧?如何将此gfs流传递给我的HTML?

1 个答案:

答案 0 :(得分:0)

我设法发出POST请求从MongoDB获取图像并将其保存在服务器目录中:

const readStream = gfs.createReadStream(files[0].filename);
const wstream = fs.createWriteStream(path.join(__dirname,"uploads", "fileToGet.jpg"));        
readStream.pipe(wstream);

然后,我只是通过添加一个绝对路径来做一个简单的GET请求,并在成功响应后最终删除该文件:

app.get('/image', function (req, res) {
  var file = path.join(dir, 'fileToGet.jpg');
  if (file.indexOf(dir + path.sep) !== 0) {
      return res.status(403).end('Forbidden');
  }
  var type = mime[path.extname(file).slice(1)] || 'text/plain';
  var s = fs.createReadStream(file);
  s.on('open', function () {
      res.set('Content-Type', type);
      s.pipe(res);
  });
  s.on('end', function () {
      fs.unlink(file, ()=>{
        console.log("file deleted");
      })
  });
  s.on('error', function () {
      res.set('Content-Type', 'text/plain');
      res.status(404).end('Not found');
  });