2

我在 imgur.com 上注册了一个应用程序(用于匿名使用),我得到了一个应用程序密钥。我在这里使用它:

self.uploadImage = function(file) {

        /* Is the file an image? */
        if (!file || !file.type.match(/image.*/)) return;

        /* It is! */
        document.body.className = "uploading";

        /* Lets build a FormData object*/
        var fd = new FormData(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
        fd.append("image", file); // Append the file
        fd.append("key", "<my key>"); // Get your own key http://api.imgur.com/
        var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com
        xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
        xhr.onload = function() {
            // reference side-specific class here
            document.querySelector("#image-uploaded-one-" + self.cardId()).href = JSON.parse(xhr.responseText).upload.links.imgur_page;

        }
        // Ok, I don't handle the errors. An exercice for the reader.

        /* And now, we send the formdata */
        xhr.send(fd);
    };

如果我使用我的密钥,我会收到一条错误消息Cannot read property 'links' of undefined,但是如果我使用在教程中找到的密钥,一切都会按预期工作。我几天前创建了密钥,所以我认为时间不是问题。还能是什么?

我认为问题在于有效的密钥是由 api 的 v2 生成的,而新的密钥是 v3,它不适用于指定的 v2。如果我指定 v3,我会得到“HTTP 访问被禁用。请求必须使用 ssl。” 我怎样才能得到这个工作?

4

1 回答 1

3

以下代码修复了它:

self.uploadImage = 函数(文件){

        /* Is the file an image? */
        if (!file || !file.type.match(/image.*/)) return;

        /* It is! */
        document.body.className = "uploading";

        /* Lets build a FormData object*/
        var fd = new FormData(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
        fd.append("image", file); // Append the file
        var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com
        xhr.open("POST", "https://api.imgur.com/3/image.json"); // Boooom!
        xhr.onload = function () {
            var response1 = JSON.parse(xhr.responseText);
            var response = JSON.parse(xhr.responseText).data.link;
            document.querySelector("#image-uploaded-one-" + self.cardId()).href = response;

        }
        // Ok, I don't handle the errors. An exercice for the reader.
        xhr.setRequestHeader('Authorization', 'Client-ID <yourkey>');

        /* And now, we send the formdata */
        xhr.send(fd);
    };
于 2013-06-06T02:19:35.073 回答