0

A user selects an image (in this case from Facebook, but I don't that is relevant to the problem). A request gets sent to the server to fetch the image and save it locally. The request resolves with 200. The resolved request is picked up on the client and the image is dynamically added to the page with JS by creating a new Image.

The problem: Even though the request does not resolve until the write process has finished, when the client tries to load the image it returns a 404.

I've tried adding an error handler on the client that reloads the image if it returns with a 404. This works after a few hundred milliseconds. However there is another problem. Often the image is only half loaded and the rest is black.

It is as if the image has not finished processing when the request resolves.

I've no idea what is causing the problem. I can't see how the request could be resolving before the operation is complete.

import fs from 'fs';
import request from 'request';
import gm from 'gm';
import createUserImageFolders from './imageHelpers/createUserImageFolders';
import getNextImageNumber from './imageHelpers/getNextImageNumber';
import saveImages from './imageHelpers/saveImages';

export default function uploadFacebookPhoto(req, params) {
  return new Promise((resolve, reject) => {
    createUserImageFolders(req.session.currentDesignerSessionId);

    const userDir = 'static/images/user/' + req.session.currentDesignerSessionId;

    const imageNumber = getNextImageNumber(userDir + '/uploads/full');

    const filename = `${userDir}/uploads/full/${imageNumber}.jpg`;

    const thumbWidth = 100;

    // Stream the image from the remote server.
    request.head(req.body.photoUrl, (err, response, body) => {
      request(req.body.photoUrl).pipe(fs.createWriteStream(filename).on(
        'close',
        () => {

          // Create thumbnail
          gm(filename)
            .noProfile()
            .quality(85)
            .resize(thumbWidth)
            .write(userDir + `/uploads/thumb/${imageNumber}.jpg`, (error) => {
              if (error) {
                console.error('Graphics Magic (gm) error ', error);
                reject({error: 500});
              } else {
                resolve(true);
              }
            });

        }
      ));
    });
  });
}
SystemicPlural
  • 5,629
  • 9
  • 49
  • 74
  • as i'm understand, you get the promise on client in place of data, you need to resolve it there. like: promiseObj.the(); – Jain Jul 09 '16 at 12:29
  • @Jain No. I'm not showing all the client server communication. Its a redux express combo. That all works fine on hundreds of other requests. When resolve(true); runs then 'true' gets sent back to the client. – SystemicPlural Jul 09 '16 at 13:51
  • can you provide more code of client – Jain Jul 09 '16 at 13:52

0 Answers0