Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - upload image binary - using imageshack api

Moving a topic from google groups to here so it can help someone who is asking.

imageshack api: http://api.imageshack.us/

the final http reqeust is returning json:

{"success":true,"process_time":325,"result":{"max_filesize":5242880,"space_limit":52428800,"space_used":0,"space_left":52428800,"passed":0,"failed":0,"total":0,"images":[]}}

which is not good, as it didn't upload :(

it should return an image object. http://api.imageshack.us/#h.ws82a1l6pp9g as this is what the upload image section on the imageshack api says

please help :(

my extension code

var blobUrl;
var makeBlob = function () {
        bigcanvas.toBlob(function (blob) {
                var reader = new window.FileReader();
                reader.readAsBinaryString(blob);
                reader.onloadend = function () {
                        blobBinaryString = reader.result;
                        blobUrl = blobBinaryString;
                        Cu.reportError(blobUrl);
                        uploadBlob();
                }
        });
};

var uploadedImageUrl;
var uploadBlob = function () {
        HTTP('POST', 'https://api.imageshack.us/v1/images', {
                contentType: 'application/x-www-form-urlencoded',
                //'album=' + urlencode('Stock History') + '&
                body: 'auth_token=' + urlencode(auth_token) + 'file@=' + blobUrl,
                onSuccess: function (status, responseXML, responseText, headers, statusText) {
                        Cu.reportError('XMLHttpRequest SUCCESS - imageshack uploadBlob
' + statusText + '
' + responseText);
                        eval('var json = ' + responseText);
                        uploadedImageUrl = json.direct_link;
                        submitBamdex();
                },
                onFailure: function (status, responseXML, responseText, headers, statusText) {
                        Cu.reportError('XMLHttpRequest FAILLLLLLLL - imageshack uploadBlob
' + statusText + '
' + responseText);
                }
        });
};


makeBlob(); //callllll the func
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

this code uploads a drawing on a canvas to imageshack

Can copy paste but have to update some things:

  • update username
  • update password
  • uploads drawing from canvas with id "bigcanvas"
  • update your API key

...

//this code uploads a drawing on a canvas to imageshack
var auth_token;
var loginImageshack = function() {
    HTTP('POST','https://api.imageshack.us/v1/user/login',{
        contentType: 'application/x-www-form-urlencoded',
        body: 'user=USERNAME_TO_IMAGESHACK_HERE&password=' + urlencode('PASSWORD_TO_USERNAME_FOR_IMAGESHACK_HERE'),
        onSuccess: function(status, responseXML, responseText, headers, statusText) {
            Cu.reportError('XMLHttpRequest SUCCESS - imageshack login
' + statusText + '
' + responseText);
            eval('var json = ' + responseText);
            auth_token = json.result.auth_token;
            makeImageshackFile();
        },
        onFailure: function(status, responseXML, responseText, headers, statusText) {
            Cu.reportError('XMLHttpRequest FAILLLLLLLL - imageshack login
' + statusText + '
' + responseText);
        }
    });
};

var uploadedImageUrl;
var makeImageshackFile = function() {
    var fd = new window.FormData();
    fd.append("api_key", 'A835WS6Bww584g3568efa2z9823uua5ceh0h6325'); //USE YOUR API KEY HERE
    fd.append("auth_token", auth_token);
    fd.append('album', 'Stock History');
    fd.append('title', 'THE-title-you-want-showing-on-imageshack')
    fd.append("file@", bigcanvas.mozGetAsFile("foo.png")); //bigcanvas is a canvas with the image drawn on it: var bigcanvas = document.querySelector('#bigcanvas');
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        switch (xhr.readyState) {
                case 4:
                    if (xhr.status==0 || (xhr.status>=200 && xhr.status<300)) {
                         Cu.reportError('XHR SUCCESS - 
' + xhr.responseText);
                        eval('var json = ' + xhr.responseText);
                        //ensure it passed else redo it I didnt program in the redo thing yet
                        //succesful json == {"success":true,"process_time":1274,"result":{"max_filesize":5242880,"space_limit":52428800,"space_used":270802,"space_left":52157998,"passed":1,"failed":0,"total":1,"images":[{"id":1067955963,"server":703,"bucket":2397,"lp_hash":"jj9g5p","filename":"9g5.png","original_filename":"foo.png","direct_link":"imageshack.us/a/img703/2397/9g5.png","title":"082813 200AM PST","description":null,"tags":[""],"likes":0,"liked":false,"views":0,"comments_count":0,"comments_disabled":false,"filter":0,"filesize":1029,"creation_date":1377681549,"width":760,"height":1110,"public":true,"is_owner":true,"owner":{"username":"bamdex","avatar":{"server":0,"filename":null}},"next_images":[],"prev_images":[{"server":59,"filename":"06mm.png"},{"server":706,"filename":"a1fg.png"}],"related_images":[{"server":59,"filename":"06mm.png"},{"server":41,"filename":"xn9q.png"},{"server":22,"filename":"t20a.png"},{"server":547,"filename":"fipx.png"},{"server":10,"filename":"dg6b.png"},{"se
                        uploadedImageUrl = json.result.images[0].direct_link;
                        Cu.reportError('succesfully uploaded image');
                    } else {
                        Cu.reportError('XHR FAIL - 
' + xhr.responseText);
                    }
                    break;
            default:
                //blah
        }
    }
    xhr.open("POST", "https://api.imageshack.us/v1/images");
    xhr.send(fd);
}

loginImageshack();

important note for code above

  • should use JSON.parse instead of eval if you want to submit the addon to AMO
  • should also probably change from using window to Services.appShel.hiddenDOMWindow so like new window.FormData(); would become new Services.appShel.hiddenDOMWindow.FormData(); OR var formData = Components.classes["@mozilla.org/files/formdata;1"].createInstance(Components.interfaces.nsIDOMFormData); OR Cu.import('resource://gre/modules/FormData.jsm')

helper functions required for the code above:

const {classes: Cc, interfaces: Ci, utils: Cu, Components: components} = Components
Cu.import('resource://gre/modules/Services.jsm');

...

function urlencode(str) {
    return escape(str).replace(/+/g,'%2B').replace(/%20/g, '+').replace(/*/g, '%2A').replace(///g, '%2F').replace(/@/g, '%40');
};

...

//http request
const XMLHttpRequest = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"];

/** 
 * The following keys can be sent:
 * onSuccess (required)  a function called when the response is 2xx
 * onFailure             a function called when the response is not 2xx
 * username              The username for basic auth
 * password              The password for basic auth
 * overrideMimeType      The mime type to use for non-XML response mime types
 * timeout               A timeout value in milliseconds for the response
 * onTimeout             A function to call if the request times out.
 * body                  A string containing the entity body of the request
 * contentType           The content type of the entity body of the request
 * headers               A hash of optional headers
 */
function HTTP(method,url,options)
{
   var requester = new XMLHttpRequest();

   var timeout = null;
   if (!options.synchronizedRequest) {

      requester.onreadystatechange = function() {
         switch (requester.readyState) {
            case 0:
               if (options.onUnsent) {
                  options.onUnsent(requester);
               }
            break;
            case 1:
               if (options.onOpened) {
                  options.onOpened(requester);
               }
            break;
            case 2:
               if (options.onHeaders) {
                  options.onHeaders(requester);
               }
            break;
            case 3:
               if (options.onLoading) {
                  options.onLoading(requester);
               }
            break;
            case 4:
               if (timeout) {
                  clearTimeout(timeout);
               }
               if (requester.status==0 || (requester.status>=200 && requester.status<300)) {
                  options.onSuccess(
                     requester.status,
                     requester.responseXML,
                     requester.responseText,
                     options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
                     requester.statusText
                  );
               } else {
                  if (options.onFailure) {
                     options.onFailure(
                        requester.status,
                        requester.responseXML,
                        requester.responseText,
                        options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
                        requester.statusText
                     );
                  }
               }
            break;
         }
      }
   }

   if (options.overrideMimeType) {
      requester.overrideMimeType(options.overrideMimeType);
   }
   if (options.username) {
      requester.open(method,url,!options.synchronizedRequest,options.username,options.password);
   } else {
      requester.open(method,url,!options.synchronizedRequest);
   }
   if (options.timeout && !options.synchronizedRequest) {
      timeout = setTimeout(
          function() {
             var callback = options.onTimeout ? options.onTimeout : options.onFailure;
             callback(0,"Operation timeout.");
          },
          options.timeout
      );
   }
   if (options.headers) {
      for (var name in options.headers) {
         requester.setRequestHeader(name,options.headers[name]);
      }
   }
   if (options.sendAsBinary) {
        Cu.reportError('sending as binary');
       requester.sendAsBinary(options.body);
   } else if (options.body) {
      requester.setRequestHeader("Content-Type",options.contentType);
      requester.send(options.body);
   } else {
      requester.send(null);
   }
   if (options.synchronizedRequest) {
      if (requester.status==0 || (requester.status>=200 && requester.status<300)) {
         options.onSuccess(
            requester.status,
            requester.responseXML,
            requester.responseText,
            options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
            requester.statusText
         );
      } else {
         if (options.onFailure) {
            options.onFailure(
               requester.status,
               requester.responseXML,
               requester.responseText,
               options.returnHeaders ? _HTTP_parseHeaders(requester.getAllResponseHeaders()) : null,
               requester.statusText
            );
         }
      }
      return {
         abort: function() {
         }
      };
   } else {
      return {
         abort: function() {
            clearTimeout(timeout);
            requester.abort();
         }
      };
   }
}
function _HTTP_parseHeaders(headerText)
{
   var headers = {};
   if (headerText) {
      var eol = headerText.indexOf("
");
      while (eol>=0) {
         var line = headerText.substring(0,eol);
         headerText = headerText.substring(eol+1);
         while (headerText.length>0 && !headerText.match(_HTTP_HEADER_NAME)) {
            eol = headerText.indexOf("
");
            var nextLine = eol<0 ? headerText : headerText.substring(0,eol);
            line = line+' '+nextLine;
            headerText = eol<0 ? "" : headerText.substring(eol+1);
         }
         // Parse the name value pair
         var colon = line.indexOf(':');
         var name = line.substring(0,colon);
         var value = line.substring(colon+1);
         headers[name] = value;
         eol = headerText.indexOf("
");
      }
      if (headerText.length>0) {
         var colon = headerText.indexOf(':');
         var name = headerText.substring(0,colon);
         var value = headerText.substring(colon+1);
         headers[name] = value;
      }
   }
   return headers;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...