我需要在 Javascript 中实现从选定区域获取元素。这是在 chrome 应用程序中制作更好的、类似桌面的 UI 所必需的。最近的例子是在 Imgur 扩展中选择区域:
所以问题是:
我正在尝试将此功能添加到我正在开发的C#Windows应用程序中,以便将图像上传到Imgur.
不幸的是,它必须是Imgur,因为该网站是必需的.
问题是,我能找到的C#示例代码是旧的,似乎不适用于他们的版本3 API.
所以我想知道在该领域有专长的人是否可以帮助我.
我更愿意使用OAuth上传,而不是匿名选项,但如果需要,后者可以用作示例.
编辑:
一部分我特别不明白的是我怎么能做出,而其余的授权步骤发生中的桌面应用程序.授权步骤需要打开网页,询问用户是否允许应用程序使用其数据.
如何为基于桌面的应用程序执行此操作?
我使用python请求模块和Imgur API将图像上传到Imgur时遇到问题.
我的代码如下:
import base64
import json
import requests
from base64 import b64encode
client_id = 'my-client-id'
headers = {"Authorization": "Client-ID my-client-id"}
api_key = 'my-api-key'
url = "http://api.imgur.com/3/upload.json"
j1 = requests.post(
url,
headers = headers,
data = {
'key': api_key,
'image': b64encode(open('1.jpg', 'rb').read()),
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
Run Code Online (Sandbox Code Playgroud)
我通常会得到400响应错误.我不确定myu client_id是否错误,或者我的请求是否错误(我对url请求的经验很少),或者我是否使用了Imgur API错误.
我提交过后,我也想获得图片的网址.我不确定API是否有命令,或者如果python.requests模块有一个技巧可以让我获取刚刚发布的数据(POST).
这里回答了一个非常相似的问题,代码确实有效!:麻烦发送文件到Imgur
但是当我使用我的client_id时,在代码中使用了应用程序ID,它返回了400错误,以及当我更改时
from:url =" http://api.imgur.com/2/upload.json "to:url =" http://api.imgur.com/3/upload.json "
我创建了UploadToImgurTask一个AsyncTask 类,它接受单个文件路径参数,创建并设置MultiPartEntity,然后使用Apache HttpClient上传带有所述实体的图像.来自Imgur的JSON响应保存在JSONObject中,我在LogCat中显示的内容供我自己理解.
这是我从Imgur收到的JSON的屏幕截图:
我在api.imgur.com上查找了错误状态401,它说我需要使用OAuth进行身份验证,尽管事实上Imgur已经明确表示如果图像是匿名上传的,应用程序不需要使用OAuth(这就是我我现在正在做
class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {
String upload_to;
@Override
protected Boolean doInBackground(String... params) {
final String upload_to = "https://api.imgur.com/3/upload.json";
final String API_key = "API_KEY";
final String TAG = "Awais";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
try {
final MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(new File(params[0])));
entity.addPart("key", new StringBody(API_key));
httpPost.setEntity(entity);
final HttpResponse response = httpClient.execute(httpPost,
localContext);
final String response_string …Run Code Online (Sandbox Code Playgroud) 我已经尝试了超过3个小时来接受基本的64位数据以至于无济于事,我已经确认数据是正确的,我已经确认我可以使用url图像发送到imgur,我只是可以不能让它发挥作用.我正在使用的代码如下:
$(document).ready(function(){
function readImage(input) {
var FR= new FileReader();
FR.onload = function(e) {
console.log(e.target.result);
$.ajax({
url: 'https://api.imgur.com/3/image',
type: 'post',
headers: {
Authorization: 'Client-ID 40dbfe0cfea73a7'
},
data: {
image: e.target.result
},
dataType: 'json',
success: function(json) {
console.log(json);
},
error: function(json) {
console.log(json);
}
});
};
FR.readAsDataURL( input );
}
});
Run Code Online (Sandbox Code Playgroud)
input是我从dropzone.js获取的表单输入,base64数据的示例是:
数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAANgAAADYCAIAAAAGQrq6AAAABnRSTlMA/gABAP1bbA07AAAD + klEQVR4nO3dMW4sNxBAQa3h + 19ZDhwzoNE0H/dXpRJGo90HBg3O8PP7 +/SDT/11 + wbg50eIRAiRBCGSIEQShEiCEEn4e/WDZ + fzf97Hf7aag9buf3deu7r/V/7fldX9WxFJECIJQiRBiCQIkQQhkiBEEpZzxJVb + xd352Sv3Odpr3wOVkQShEiCEEkQIglCJEGIJAiRhO054srU/Gxq7nV67rh7/dp8sfZ9WRFJECIJQiRBiCQIkQQhkiBEEsbmiDWnn/+ dur73U/7LikiCEEkQIglCJEGIJAiRBCGS8LVzxF277yN8/E/WWBFJECIJQiRBiCQIkQQhkiBEEsbmiLW519Q5Jbee/z09X6x9X1ZEEoRIghBJECIJQiRBiCQIkYTtOWLtPX + n7c4dp35/yivflxWRBCGSIEQShEiCEEkQIglCJOFT25d2y + k5X + 1ckxorIglCJEGIJAiRBCGSIEQShEjCcj9ibb/d1PklU + csn36 + eGruOHX/p3uwIpIgRBKESIIQSRAiCUIkQYgkLOeItedta + 81rM3npty6HysiCUIkQYgkCJEEIZIgRBKESMLxc1ZunXdy + n523br + …
我正在使用 Imgur API 上传图像。他们在API 文档中详细说明,每个请求(当我通过他们的 API 上传图像时)也有响应标头,这将告诉我该帐户还剩多少信用额。
我需要返回 HTTP 响应标头X-RateLimit-ClientRemaining。这是我当前用来获取 cURL 正文的代码:
$filename = dirname(realpath(__FILE__))."/images/$value";
$client_id = "f*************c";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$pvars = array('image' => base64_encode($data));
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$out = curl_exec($curl);
curl_close ($curl);
$pms = json_decode($out,true);
$url=$pms['data']['link'];
if($url!=""){
// add to success
array_push($success, $url);
} …Run Code Online (Sandbox Code Playgroud) 我正在使用的项目:来自nuget的ImgurNet(来源:https ://github.com/0xdeafcafe/ImgurNet )
看起来它需要所有这些参数:
{
"client_id": "Insert your imgur client_id here",
"client_secret": "Insert your imgur client_secret here",
"access_token": "Insert your imgur access_token here",
"refresh_token": "Insert your imgur refresh_token here",
"authorized_username": "Insert your imgur username here"
}
Run Code Online (Sandbox Code Playgroud)
...而在 imgur 中我只能得到client_id+ client_secret。
Imgur API 文档提到了这些,但没有说明如何获取它们:https://api.imgur.com/oauth2
额外细节:
我使用它是ImgurNet因为它是我能够在 Xamarin 项目中安装的唯一 imgur api nuget 包(所有其他包都不兼容)。
这是我正在使用的代码的示例:
var oauth2Authentication = new OAuth2Authentication("my_client_id", "my_client_secret", false);
var imgurClient = new Imgur(oauth2Authentication);
var imageEndpoint = new ImageEndpoint(imgurClient);
var result = imageEndpoint.UploadImageFromBinaryAsync(imageBinary, …Run Code Online (Sandbox Code Playgroud) 我不是在开发Android应用程序,
而是在编写一些JAVA代码来支持Imgur API服务。
public interface ImgurAPI {
String server = "https://api.imgur.com";
String BASE64 = "base64";
@POST("/3/upload")
void postImage(
@Header("Authorization") String auth,
@Query("title") String title,
@Query("description") String description,
@Query("type") String type,
@Body String base64Image,
Callback<ImageResponse> cb
);
Run Code Online (Sandbox Code Playgroud)
}
主要:
public static void main(String[] args) {
try{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ImgurAPI.server)
.build();
ImgurAPI myAPI = retrofit.create(ImgurAPI.class);
String base64Image = new ImageReader(PATH).getBase64String();
myAPI.postImage(AUTH, "Hi", "Test", ImgurAPI.BASE64, base64Image, new MyCallBack());
}catch(Exception err){
err.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
和异常抛出:
Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/Call$Factory …Run Code Online (Sandbox Code Playgroud) 我可以创建专辑,使用requests和oauth-hook模块就好了,但我似乎无法获得一个名称。在此处查看文档:http : //api.imgur.com/resources_auth#account_albums。我使用的是 Windows7x64 Python2.7,requests版本 0.21.1 和oauth-hook版本 0.4.0
奇怪的是,当我上传图像时使用相同的方法命名图像,脚本工作得很好。这是相关的代码:
client = requests.session(hooks={'pre_request': authorizedHook})
url = r'http://api.imgur.com/2/account/albums.json'
parameters = {'title': 'ALBUMTITLEHERE'}
r = client.post(url, data=parameters)
Run Code Online (Sandbox Code Playgroud)
一旦我将它加载到json:
Created Album data:
{u'albums': {u'anonymous_link': u'http://imgur.com/a/i3Gal',
u'cover': u'',
u'datetime': u'2012-05-24 02:34:42',
u'description': u'',
u'id': u'i3Gal',
u'layout': u'blog',
u'link': u'http://tankorsmash.imgur.com/1B498',
u'order': 0,
u'privacy': u'public',
u'title': u''}}
Run Code Online (Sandbox Code Playgroud)
我期待的是一个名为ALBUMTITLEHERE. 而是创建了一个未命名的。我究竟做错了什么?
无关:Stats API 似乎根本没有为我返回任何东西,但我不确定这是否相关。
尝试上传用户图像但没有成功。
HTML:
前端JS:
var fileInput = document.getElementById('gg_test_input');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append("file", file);
xhr.open('POST', '/gg_upload');
xhr.send(formData);
});
Run Code Online (Sandbox Code Playgroud)
我们向 Node.js 发送请求:
函数(req,res){ var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if( err ) throw err;
unirest.post('http://httpbin.org/post')
.header("X-Mashape-Key", "MASHAPE_KEY")
.header("Authorization", "clientID_KEY")
.attach('file', files.file.path)
.end(function (response) {
console.log(response.status, response.headers, response.body);
});
});
Run Code Online (Sandbox Code Playgroud)
}
但我得到的是:
403 { 'access-control-allow-headers': 'Authorization, Content-Type, Accept, X-Mashape-Authorization',
'access-control-allow-methods': 'GET, PUT, POST, DELETE, OPTIONS',
'access-control-allow-origin': …Run Code Online (Sandbox Code Playgroud)