【问题标题】:Firefox treating pasted image from clipboard as a string instead of fileFirefox 将剪贴板中粘贴的图像视为字符串而不是文件
【发布时间】:2022-06-21 13:17:33
【问题描述】:

我正在尝试从 contenteditable div 的粘贴事件中获取图像。它在 chrome 中运行良好,但在 Firefox 中无法运行。 我正在使用以下代码:

$(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] 在 Firefox 中包含 text/plain 类型的数据,而在 chrome 中是 image/png。 (对于 png 图像上传) `

【问题讨论】:

    标签: javascript jquery firefox cross-browser clipboard


    【解决方案1】:

    我刚刚打了这个。也许在粘贴图像时,第一项始终是图像项。现在不是这样了。

    我现在首先得到text/plain,如果从网络上复制,它会包含图像的 URL。然后是text/html,最后是image/png,例如。所以你必须先找到正确的项目,然后再继续。

    const item = [...data.items].find((i) => i.type.includes("image"));
    

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 2022-06-23
      • 2011-01-03
      相关资源
      最近更新 更多