Imgur API错误,如何用XHR上传
Imgur API Error, How to upload with XHR
var fd = new FormData();
fd.append("image", file); // Append the file
fd.append("key", API_KEY);
// Create the XHR (Cross-Domain XHR FTW!!!)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
xhr.onload = function() {
console.log(JSON.stringify(xhr.responseText));
alert("Anything?");
var img_url = JSON.parse(xhr.responseText).upload.links.original;
console.log("Image url of the uploaded image" + img_url);
上面的代码是我用来通过phonegap上传图像文件的代码。但我猜代码是过时的,不能与最新的imgur API一起工作。由OAuth支持。我可以知道如何修复它,以便上传图像吗?
你是对的…代码是过时的,所以我固定的方式是匿名上传图像与以下说明:
1。-在FormData
中,你只需要附加图像,所以键不应该附加
2。-你必须发送一个带有你的客户端id的标题,我想你已经有了…我用下面的代码xhr.setRequestHeader('Authorization', 'Client-ID FOO');
来做根据文档,它必须在打开XMLHttpRequest
之后,但在发送请求之前。
3。-当你试图获得链接时,你必须解析JSON以便读取信息,链接来自data
节点,名称为link
,因此解析将是:var link = JSON.parse(xhr.responseText).data.link;
4。-你必须使用OAuth 2.0的新稳定API,所以你上传图像的行应该看起来像这样:xhr.open("POST", "https://api.imgur.com/3/image.json");
…正如你所看到的,它只是改变了数字,这是版本,而不是upload
,它使用image
,它必须是https
…供您参考,这是第一种建议的方法,另一种建议的方法,也有效,如下:xhr.open("POST", "https://api.imgur.com/3/upload.json");
function upload(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();
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() {
// Big win!
var link = JSON.parse(xhr.responseText).data.link;
document.querySelector("#link").href = link;
document.querySelector("#link").innerHTML = link;
document.body.className = "uploaded";
}
// Ok, I don't handle the errors. An exercice for the reader.
xhr.setRequestHeader('Authorization', 'Client-ID FOO');
/* And now, we send the formdata */
xhr.send(fd);
}
我鼓励你看一下文档,它非常友好,帮助你创建函数和东西…正如我所说的,这是匿名上传,如果你想用用户上传图像,你必须先用用户和密码进行身份验证,使用令牌,并刷新它们,我没有这样做,但一旦你了解了它是如何工作的,它应该不会太复杂…
希望有帮助!!
- 如何用更合适的内容替换document.write
- 如何用javascript获取谷歌地图的经度和纬度
- 分页:如何用AJAX加载第一个页面
- 中止POST XHR可靠
- 如何用低音量自动启动Youtube视频(iframe)
- 如何用另一个Javascript更改Javascript函数值
- 如何用javascript打印php数组
- Dojo XHR将200 OK视为错误
- 如何用d3.js绘制折线图
- Javascript/AngularJs-如何用另一个数组中的对象填充数组
- AngularJS:如何用同一对象的另一个属性访问一个属性
- Chrome扩展:XHR后关闭窗口
- 如何用moment.js列出两个日期之间的所有月份
- 如何用jquery替换字符串中可能变化的字符
- 如何用javascript下载画布图像(base64)
- 如何用JavaScript或jQuery替换一堆标签
- XHR不适用于聊天应用程序
- 我如何用纯JavaScript取代jQuery的toggleClass方法
- 如何用javascript重写html文档
- Imgur API错误,如何用XHR上传