How to detect heic image before upload in JavaScript on iOS11?
Asked Answered
S

1

21

We have an image uploading application and we compress images on client side using an external JavaScript library before uploading.

Now we have came across an issue specific to iOS11 when uploading image files having the extension of .heif or .heic.

As an example when we submit the form with abc.heic image, client side browser application crashes when trying to compress it through above library. So we want to restrict attaching .heic images to the image input.

Unfortunately we cannot identify (I think so) .heic images on server side, because we receive file name as abc.jpgon backend since iOS11 automatically convert .heic images into jpg images before uploading.

Therefore I want to detect it on client side, but when I check file MIME type on client side using below code, it returns image/jpg (actually I don't have an iPhone, so some other friend did it for me). So it looks like .heic image is already converted to jpg internally by iOS11 before I check MIME type. (But for some reason, those converted jpg files are not able to compress by this library)

$(document).on('change', '[id=uploading_file]', (evt) => {
    'use strict'
    const files = [...evt.target.files];
    var uploadingFile = files[0];
    var fileType = uploadingFile["type"]; // get file MIME type
    var ValidImageTypes = ["image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp"];

    if (jQuery.inArray(fileType, ValidImageTypes) >= 0) {
        // image compression code goes here.
    }
});

Some alternative solution:

I did some other alternative fix also to avoid attaching .heic images as below though it is not a guaranteed solution. Changed accept="image/*" to accept="image/jpg, image/jpeg, image/png, image/gif, image/bmp" , but it still shows abc image on file chooser.

Spoonful answered 1/6, 2018 at 5:50 Comment(0)
A
2

It's not as robust as using the mime type, but you can use the heic and/or heif extension to restrict which files can be selected.

For instance:

<input type="file" accept=".heic">

Allieallied answered 20/11, 2019 at 17:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.