Firefox treating pasted image from clipboard as a string instead of file

Viewed 216

I am trying to get image from on paste event from a contenteditable div. It is working fine in chrome but isn't working in firefox. I am using the following code:

$(window).on("paste", function(e) {
    const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
    if(e.originalEvent.clipboardData.items.length!=0)
    {
        let file = e.originalEvent.clipboardData||e.clipboardData).items[0].getAsFile();
            var upload_url = "{% url 'api:v2:images:upload' %}?format=json";
            if (file)
            {
                var fileType = file['type'];
                if (validImageTypes.includes(fileType)) {
                    var data = new FormData();
                    data.append('qqfile', file);
                    $.ajax({
                            type: 'POST',
                            processData: false, // important
                            contentType: false, // important
                            data: data,
                            url: upload_url,
                            dataType : 'json',
                            async: false,
                            success: function(jsonData){
                                var new_tag = "<img src=\""+jsonData.url+"\" data-verified=\"redactor\" data-save-url=\""+jsonData.filelink+"\" style=\"opacity: 0.5;\">";
                                 setTimeout(insertTextAtCaret(new_tag),0);
                             }
                         });
                }
                e.preventDefault();
            }
        }
     });

e.originalEvent.clipboardData.items[0] contains data of type text/plain in firefox whereas, it is image/png in chrome. (For a png image upload) `

1 Answers

I just hit this. Perhaps at one point when pasting an image the first item was consistently the image item. That's not the case now.

I now get text/plain first which has the URL of the image if copied from the web. Then text/html, and finally image/png for example. So you'll have to find the correct item first and then proceed.

This is untested and plucks the first image type of match. You could perhaps extend it to only pick one of the valid types.

const data = (e.originalEvent.clipboardData||e.clipboardData);
const item = [...data.items].find((i) => i.type.includes("image"));
const file = item.getAsFile();
Related