我想使用他们的API将图片上传到imgur;使用javascript(node.js)。 我总是把它作为回应:
{"数据":{"错误":"图片格式不受支持,或图片已损坏。","请求" :" / 3 /上传""方法":" POST"}"成功":假,"状态&#34 ;:400}
这是我写的代码:
ImgUrlHelper =
{
InitUploadValidateFile :function(element)
{
var file = element.value;
if(file === "")
return;
if(file != '')
{
var valid_extensions = /(.jpg|.jpeg|.gif|.png)$/i;
if(valid_extensions.test(file))
{
console.log("ok");
this.Upload(file);
}
else
console.log("notok");
}
else
console.log("notok");
},
Upload: function(file) {
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.imgur.com/3/upload", true);
xhr.onload = this.OnLoad;
xhr.onerror = this.OnNetworkError;
xhr.onreadystatechange = this.OnReadyStateChange;
xhr.onprogress= this.OnProgress;
xhr.setRequestHeader('Authorization', 'Client-ID xxxxxxxxxxxx');
xhr.send(fd);
},
OnReadyStateChange:function(xhr){
if(xhr.readyState == 4 && xhr.status == 200)
{
var link = JSON.parse(xhr.responseText).data.link;
console.log(link);
}
if(xhr.status != 200)
{
console.log(xhr.status);
//log error
}
},
OnNetworkError:function(xhr)
{
//log error
console.log("network error while uploading.");
console.log(xhr);
},
OnProgress : function(e)
{
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
},
OnLoad : function(res) {
}
}
我通过在输入类型="文件"上使用onchange事件来调用它:
onchange="ImgUrlHelper.InitUploadValidateFile(this)"
我认为读取我使用文件上传控件选择的文件时出现问题,此处:
fd.append("image", file);
此时,文件包含字符串:" C:\ fakepath \ img.jpg"。我可能需要对图像进行实际编码吗?
答案 0 :(得分:2)
您应该上传File
个对象,而不是字符串。
将var file = element.value;
更改为var file = element.files[0];
:
// assuming that element is an <input type=file>
InitUploadValidateFile: function(element) {
var file = element.files[0];
if (!file)
return;
var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.png)$/i;
if (valid_extensions.test(file.name)) {
console.log("ok");
this.Upload(file);
} else {
console.log("notok");
}
},