本文介绍了上传图像二进制 - 使用imageshack api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将一个主题从Google群组移到这里,这样可以帮助某个人询问。



imageshack api:



最后的http reqeust正在返回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:[]}} 

这并不好,因为它没有上传:($ / b
$ b

image object。
,因为这是在imageshack api上的上传图片部分所说的:

请帮忙:($ / b>

代码

  var blobUrl; 
var makeBlob = function(){
bigcanvas.toBlob(function(blob ){
var reader = ne w 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 urlencode('Stock History')+'&
body:'auth_token ='+ urlencode(auth_token)+'file @ ='+ urlencoded',
//'album ='+ urlencode blobUrl,
onSuccess:function(status,responseXML,responseText,headers,statusText){
Cu.reportError('XMLHttpRequest SUCCESS - imageshack uploadBlob \ n'+ statusText +'\ n'+ responseText) ;
eval('var json ='+ responseText);
uploadedImageUrl = json.direct_link;
submitBamdex();
},
onFailure:function(status, responseXML,responseText,headers,statusText){
Cu.reportError('XMLHttpRequest FAILLLLLLLL - imageshac k uploadBlob\\\
'+ statusText +'\ n'+ responseText);
}
});
};


makeBlob(); // callllll the func


解决方案

此代码上传

可以复制粘贴,但必须更新一些内容:




  • 更新用户名

  • 更新密码

  • b
  • 更新您的API密钥



  • ...

      //这段代码将一幅画布上传到ima​​geshack 
    var auth_token;
    var loginImageshack = function(){
    HTTP('POST','https://api.imageshack.us/v1/user/login',{
    contentType:'application / x (),
    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 +'\ n'+ 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'); //使用您的API密钥
    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是绘制图像的画布: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);
    //确保它通过了其他的重做它我没有编程重做的东西尚未
    //成功json == {成功:真正的,process_time:1274,结果:{max_filesize :5242880, SPACE_LIMIT :52428800, SPACE_USED :270802,space_left :52157998, 合格 :1, 失败 :0, 总 :1, 图像 :[{ ID: 1067955963, 服务器:703, 桶:2397, lp_hash: jj9g5p, 文件名: 9g5.png, original_filename: foo.png, direct_link:imageshack.us \ / a \ / img703 \ / 2397 \ / 9g5.png,title:082813 200AM PST,description:null,tags:[],likes:0 , 喜欢:假, 意见:0, comments_count:0 comments_disabled:假, 过滤器:0, 文件大小:1029, CREATION_DATE:1377681549, 宽度:760,高度 :1110, 公共 :真实的, is_owner :真正的 主人 :{ 用户名 : bamdex 阿凡达:{ 服务器:0, 文件名:空}}, next_images :[], prev_images :[{ 服务器 :59, 文件名 : 06mm.png },{ 服务器 :706, 文件名 : a1fg.png }], related_images :[{ 服务器 :59, 文件名 : 06mm.png },{ 服务器:4 1, 文件名: xn9q.png},{ 服务器:22, 文件名: t20a.png},{ 服务器:547, 文件名: fipx.png},{ server:10,filename:dg6b.png},{se
    uploadedImageUrl = json.result.images [0] .direct_link;
    Cu.reportError('成功上传的图片');
    } else {
    Cu.reportError('XHR FAIL - \\\
    '+ xhr.responseText);
    }
    break;
    default:
    // blah
    }
    }
    xhr.open(POST,https://api.imageshack.us/v1/images );
    xhr.send(fd);
    }

    loginImageshack();

    重要注意事项
    $如果您要将插件提交到

  • 也可能从使用窗口更改为 Services.appShel.hiddenDOMWindow 类似于 new window.FormData(); 会变成 new Services.appShel.hiddenDOMWindow.FormData(); OR var formData = Components.classes [@ mozilla.org/files/formdata;1]。createInstance(Components.interfaces.nsIDOMFormData); OR Cu.import('resource://上面代码所需的辅助函数:




  const {类:Cc,接口:Ci,utils:Cu,Components:组件} =组件
Cu.import('resource://gre/modules/Services.jsm');

...

替换(/%20 / g,'+')。 replace(/ \ * / g,'%2A')。replace(/ \ // g,'%2F')。replace(/ @ / g,'%40'); 
};

...

  // http请求
const XMLHttpRequest = Cc [@ mozilla.org/xmlextras/xmlhttprequest; 1];
$ b / **
*可以发送以下密钥:
* onSuccess(必需)当响应是2xx时调用的函数
* onFailure函数调用时响应不是2xx
* username基本身份验证的用户名
* password基本身份验证的密码
* overrideMimeType用于非XML响应的MIME类型mime类型
* timeout响应的超时值(以毫秒为单位)
* onTimeout在请求超时时调用的函数。
* body包含请求的实体主体的字符串
* contentType请求的实体主体的内容类型
*头部可选头部的哈希
* /
function HTTP(method,url,options)
{
var request = 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;
情况2:
if(options.onHeaders){
options.onHeaders(requester);
}
break;
案例3:
if(options.onLoading){
options.onLoading(requester);
}
break;
case 4:
if(timeout){
clearTimeout(timeout); (请求者状态== 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){
(options.headers中的var名称){
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&&&requestester.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();
}
};

$ b $ 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); (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);
}
//解析名称值对
var colon = line.indexOf(':');
var name = line.substring(0,冒号);
var value = line.substring(冒号+ 1);
headers [name] = value;
eol = headerText.indexOf(\\\
);

if(headerText.length> 0){
var colon = headerText.indexOf(':');
var name = headerText.substring(0,冒号);
var value = headerText.substring(冒号+ 1);
headers [name] = value;
}
}
返回头文件;
}


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.ws82a1l6pp9gas 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\n' + statusText + '\n' + responseText);
                        eval('var json = ' + responseText);
                        uploadedImageUrl = json.direct_link;
                        submitBamdex();
                },
                onFailure: function (status, responseXML, responseText, headers, statusText) {
                        Cu.reportError('XMLHttpRequest FAILLLLLLLL - imageshack uploadBlob\n' + statusText + '\n' + responseText);
                }
        });
};


makeBlob(); //callllll the func
解决方案

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\n' + statusText + '\n' + 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\n' + statusText + '\n' + 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 - \n' + 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 - \n' + 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("\n");
      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("\n");
            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("\n");
      }
      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;
}

这篇关于上传图像二进制 - 使用imageshack api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:59