Question

I registered an application over at imgur.com (for anonymous usage) and I got an application key. I'm using it here:

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);
    };

If I use my key, I get an error saying Cannot read property 'links' of undefined, however if I use one I found on a tutorial, everything works as expected. I created the key a few days ago so I don't think timing is the issue. What else could it be?

I think the issue is that the key that works was generated by v2 of the api, and the new ones are v3, which won't work with v2 specified. If I specify v3, I get "HTTP Access is disabled. Requests must use ssl." How can I get this working?

Was it helpful?

Solution

The following code fixed it:

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
        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);
    };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top