1

I am using Multer to store uploaded files into /uploads/ folder and also GraphicsMagick to store thumbnails in /thumbs/. When I use css to display thumbnails in the page it works fine but when I try to display the gm-created thumbnails it fails sporadically if there is more than one file. Here is the server.js part:

var express    = require('express');
var multer = require('multer');
var app        = express(); 
var bodyParser = require('body-parser');    
var morgan     = require('morgan'); 
var mongoose   = require('mongoose');
var config     = require('./config');
var path       = require('path');
var fs         = require('fs');
var gm         = require('gm');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads/'); 
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
    console.log('multer file originalname = ' + file.originalname);
    gm('./public/uploads/' + file.originalname)
    .resize(100, 100)
    .gravity("Center")
    .extent(100, 100)
    .quality(75)
    .noProfile()
    .write('./public/thumbs/' + file.originalname, function (err) {
        if (err) console.log(err);
    });
}
});
var upload = multer({ storage: storage });

app.post('/', upload.array('file'), function(req, res){
    res.status(204).end();
});

There are no errors being reported and the files are saved correctly in /uploads/ and /thumbs/. I tried using a $timeout on the $location.path('/display'); which loads the target path but no difference. Here is the display.html part:

<div ng-repeat="f in display.files">
        <div id="image_thumb">
        <a ng-href="/uploads/{{f}}" target="_blank"><img src="/thumbs/{{f}}"></a>
        <br><br>
        <p id="thumbname">{{f}}</p>

Like I say if I use css to display the thumbs as:

<div ng-repeat="f in display.files">
        <div id="image_thumb">
        <a ng-href="/uploads/{{f}}" target="_blank"><img src="/uploads/{{f}}" class="displaythumb"></a>
        <br><br>
        <p id="thumbname">{{f}}</p>

there is no problem, so it is the way I am using (misusing) gm that is at fault. Can someone help please.

meanstacky
  • 387
  • 1
  • 8
  • 18

1 Answers1

3

The problem here was that multer had not finished saving the files to the /uploads/ folder when gm was trying to get the files for making thumbs, so the answer was to move the gm code block to the app.post function so gm now can get stored files only and no errors:

app.post('/', upload.array('file'), function(req, res){
    req.files.forEach(function(imageValues, key) {
        var filename = imageValues.filename;
        gm('./public/uploads/' + filename)
        .resize(100, 100)
        .gravity("Center")
        .extent(100, 100)
        .quality(75)
        .noProfile()
        .write('./public/thumbs/' + filename, function (err) {
            if (err) console.log(err);
        }); 
    });
    res.status(204).end();
});
meanstacky
  • 387
  • 1
  • 8
  • 18