0

I encountered a problem with image upload through iOS devices. Every time I take a photo from the phone and try to upload it to my S3 bucket with multer-sharp-s3, it rotates it horizontally. Now I have read the image on this site: https://imgops.com/, and saw it says Orientation to be Horizontal (normal). In my code I can put rotate option on multer which will fix the rotation of iOS images, but will also rotate from any other sources. See bellow it is commented out // rotate: 90

This is my multer middleware:

exports.uploadImages = multer({
  storage: multerS3sharp({
    s3,
    Bucket: process.env.AWS_S3_BUCKET_NAME,
    ACL: 'public-read', // public access
    cacheControl: 'max-age=31536000',
    contentType: multerS3sharp.AUTO_CONTENT_TYPE,
    // withMetadata: true,
    metadata: (req, file, cb) => {
      cb(null, { fieldName: file.fieldname });
    },
    Key: (req, file, cb) => {
      cb(null, 'images/' + Date.now().toString() + '_' + file.originalname);
    },
    // rotate: 90,
    // multiple: true,
    // resize: {
    //   width: null,
    //   height: null,
    // },
  }),
  limits: {
    files: 1,
    fileSize: 5 * 1024 * 1024, // 5mb limit
  },
  fileFilter: (req, file, cb) => {
    if (!file.mimetype.includes('image' || 'svg')) {
      return cb('Sorry, images only');
    }
    cb(null, true);
  },
});

This is my routes file:

app.patch(jwt.checkToken, permit(['admin', 'user']), uploadImages.single('image'), controller.editWeek);

And this is my controller:

exports.editWeekGallery = async (req, res) => {
  const { pregnancyID } = req.params;
  const { weekNumber } = req.query;

  if (!pregnancyID) {
    return res.status(200).json({ message: 'Missing pregnancyID path param' });
  }

  if (!weekNumber) {
    return res.status(200).json({ message: 'Missing weekNumber query param' });
  }

  // if (!req.file) {
  //   return res.status(200).json({ message: 'Missing image form-data body param' });
  // }

  try {
    const image = req.file && req.file.Location ? req.file.Location : null;

    await Pregnancy.PregnancyData.updateOne(
      { _id: pregnancyID, 'gallery.weekNumber': +weekNumber },
      { 'gallery.$.image': image },
    );

    return res.status(200).json({ message: `Week ${weekNumber} image updated`, image });
  } catch (error) {
    console.log(error);
    return res.status(500).json({ error: error.message });
  }
};

I have read multiple articles and answers like these: iOS Image Orientation has Strange Behavior, uploaded images from iPhone show up sideways because of exif data, but I don't understand and know what to do and how to implement what is needed.

Can the problem be handled on backend or it must be from frontend (on front using React Native)?

Thank you for you help!

Shoone
  • 11
  • 3

0 Answers0