-1

I decided to post this after extensive searching here (1, 2, 3 ) and here (1, 2) and many, many other related posts. I am loosing hope, but will not give up that easily :)

I'm using multer to upload a PNG image to mongo database:

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');

Then I create a stream and pipe it to response:

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 request to end point results in response body being displayed as an image file:

enter image description here

In the front end I pass the response in a File object, read it and save the result in a src attribute of img:

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));

        }

My File object is similar to the one I get when using input field only bigger: enter image description here

This is original file: enter image description here

When inspecting element I see this: enter image description here

Looks like data URI is where it should be, but it's different from the original image on file input: enter image description here

Again, when I want to display it through input element:

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);   
}

I get this:

enter image description here

But when reading it from the response, it is corrupted:

enter image description here

Postman gets it right, so there must be something wrong with my front-end code, right? How do I pass this gfs stream to my html?

besthost
  • 759
  • 9
  • 14
  • I managed to make a POST request to write a file to the server first: ``var wstream = fs.createWriteStream(path.join(__dirname,"uploads", "fileToGet.jpg")); readStream.pipe(wstream);`` – besthost Jun 12 '18 at 20:46

1 Answers1

0

I managed to make a POST request to fetch an image from MongoDB and save it in the server dir:

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

Then, I just made a simple GET request by adding an absolute path to the and finally delete the file after successful response:

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');
  });
besthost
  • 759
  • 9
  • 14