[英]Problem with Wordpress plugin sending base64 image data via Ajax - 400/404/500 errors
[英]Ajax API Request returns 400 with base64 image data
我正在嘗試使用Imgur API在我的網站上創建一個功能,當我寫博客文章時,我可以將圖像拖到<textarea>
,然后將其上傳到Imgur並將鏈接插入textarea對我來說。 此功能使用HTML5的Draggable / Droppable功能,新的FileReader
對象和jQuery AJAX。
到目前為止,當我使用$.ajax()
向API發送請求時,API會返回400個錯誤,並顯示消息“文件類型不受支持或圖像已損壞”。 但是,我知道我的圖像的文件類型是受支持的( data/png
),並且FileReader
生成的數據沒有損壞,因為我可以將數據粘貼到我的URL欄中並獲取我插入的圖片。
$(document).ready(function(e) {
var area = document.getElementById('post_body');
function readFiles(files) {
console.log("readfiles called! files: ");
console.log(files);
var fr = new FileReader();
fr.onload = function(event) {
console.log(event);
var dat = "{image:'"+event.target.result+"'}";
console.log(dat);
$.ajax({
type:"POST",
data:dat,
url:'https://api.imgur.com/3/image',
headers: {
Authorization: "Client-ID CLIENT-ID-WAS-HERE"
},
contentType: "text/json; charset=utf-8",
dataType: "json",
success:function(msg) {
console.log(msg);
area.innerHTML += msg.data;
},
error:function(errormsg) {
console.log(errormsg);
alert("Sorry, there was an error uploading the image." + errormsg.responseText);
}
});
}
fr.readAsDataURL(files[0]);
}
area.ondragover = function(e) {
e.preventDefault();
console.log("ondragover fired!");
$(this).addClass('hover');
}
area.ondragend = function(e) {
e.preventDefault();
console.log("ondragend fired!");
$(this).removeClass('hover');
}
area.ondrop = function(e) {
console.log("ondrop fired!!");
if ($(this).hasClass('hover')) $(this).removeClass('hover')
e.preventDefault();
readFiles(e.dataTransfer.files);
}
});
Imgur API可能不接受JSON數據字符串; 它可能只接受表單樣式的POST數據有效負載
image=fQas3r...&type=base64&title=Cats%20Forever
但是你傳給它一個JSON字符串。
如果你把它的實際對象換成data
而不是JSON字符串,jQuery會自動格式化你的有效負載:
var datObj = { image: event.target.result };
$.ajax({
type: "POST",
data: datObj,
...
此外,由於您正在查找表單數據字符串而不是JSON,因此請從Ajax請求中刪除contentType
參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.