Firefox 插件正在上传 canvas 内容到 imgur

Firefox addon uploading canvas contents to imgur

我正在用 firefox 编写一个插件,自动将 canvas 的内容发送到 imgur。我已经在 chrome 中构建了一个类似的扩展,它按预期工作,所以我知道 imgurs API 的用法是正确的。当我在 Firefox 插件中使用相同的方法时,我总是得到这样的响应:

{
"data": {
    "error": "Image format not supported, or image is corrupt.",
    "request": "/3/upload",
    "method": "POST"
},
"success": false,
"status": 400
}

这是我用来提取图像数据并将其发送到 imgur API:

Request({
   url: 'https://api.imgur.com/3/upload',
   contentType : 'json',
   headers: {
       'Authorization': 'Client-ID ' + imgurClientID
   },
   content: {
   type: 'base64',
   key: imgurClientSecret,
   name: 'neon.jpg',
   title: 'test title',
   caption: 'test caption',
   image: getImageSelection('image/jpeg').split(",")[1]
},
onComplete: function (response) {
    if (callback) {
       callback(response);
    } else {
         var win = window.open(response['data']['link'], '_blank');
         win.focus();
         closeWindow();
    }
}


}).post();

这用于从 canvas 中获取选择并获取该选择的 dataurl:

function getImageSelection(type) {
    //Create copy of cropped image
    var mainImageContext = mainImage.getContext('2d');
    var imageData = mainImageContext.getImageData(selection.x, selection.y, selection.w, selection.h);

    var newCanvas = tabDocument.createElement("canvas");
    newCanvas.width = selection.w;
    newCanvas.height = selection.h;

    newCanvas.getContext("2d").putImageData(imageData, 0, 0);

    return mainImage.toDataURL(type)
}

我已经尝试了一切:使用原始 canvas (mainImage) 中的 dataurl,获取没有任何类型的 dataUrl,这个:.replace(/^data:image\/(png|jpg);base64,/, "");

但是 imgur 一直抱怨格式错误。

最后发现是Firefox addon SDK的Request模块使用错误

您必须使用 dataType,而不是使用 contentType 来提供内容的类型(如 jquery/ajax)。见下文:

Request({
        url: 'https://api.imgur.com/3/upload',
        dataType : 'json',
        headers: {
            'Authorization': 'Client-ID ' + imgurClientID
        },
        content: {
            type: 'base64',
            key: imgurClientSecret,
            name: 'neon.jpg',
            title: 'test title',
            caption: 'test caption',
            image: getImageSelection('image/jpeg', true)
        },
        onComplete: function (response) {
            response = JSON.parse(response.text);
            if (callback) {
                callback(response);
            } else {
                var win = window.open(response['data']['link'], '_blank');
                win.focus();
                closeWindow();
            }
        }
    }).post();