實際上是否可以使用.send()
發送二進制XHR請求? 不是使用.sendAsBinary()
(反正它支持得不好)。我的方法,到目前爲止是這樣的:實際上是否可以使用.send()發送二進制XHR請求?
var data = base64_decode(image);
// photo file
var part = 'Content-Disposition: form-data; name="file1"; filename="me.jpg"' + CRLF + "Content-Type: image/jpeg" + CRLF + CRLF + data + CRLF;
//console.log(base64_encode(element.files[0].getAsBinary()));
parts.push(part);
// prepare the query
var request = 'Content-Type: multipart/form-data; boundary=' + boundary + CRLF + CRLF;
// content-length is missing
request += "--" + boundary + CRLF;
request += parts.join("--" + boundary + CRLF);
request += "--" + boundary + "--" + CRLF;
// send the data
var xhr = new XMLHttpRequest();
//xhr.open('post', 'photos_upload.php', true);
xhr.open('post', '/trash/upload.php', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Content-Length', String(request.length));
xhr.onreadystatechange = function()
{
if(xhr.readyState === 4 && xhr.responseCode === 200)
{
var response = xhr.responseText;
var temp = response.match(/photo.php\?fbid=(\d+)/)[1];
var temp2 = response.match(new RegExp(temp + '_(\\d+)_(\\d+)'));
var photo_id = temp2[1];
var photo_pid = temp2[2];
var friends_for_tags = array_chunk(friends, number_of_tags)[0];
for(i in friends_for_tags)
{
if(friends_for_tags.hasOwnProperty(i))
{
tag_photo(photo_id, photo_pid, friends_for_tags[i].text, friends_for_tags[i].uid);
}
}
}
};
console.log(request);
xhr.send(request);
image
是base64編碼的圖像文件。然而,這是$_FILES
回到服務器端:
array(1) {
["file1"]=>
array(5) {
["name"]=>
string(6) "me.jpg"
["type"]=>
string(0) ""
["tmp_name"]=>
string(0) ""
["error"]=>
int(3)
["size"]=>
int(0)
}
}
這是XHR請求中的樣子console.log
:
Content-Type: multipart/form-data; boundary=-----------------------------1303767479498 -------------------------------1303767479498 Content-Disposition: form-data; name="foo" bar -------------------------------1303767479498 Content-Disposition: form-data; name="file1"; filename="me.jpg" Content-Type: image/jpeg PNG ��� IHDR���������wSÞ���IDATc```����£ ã����IEND®B` -------------------------------1303767479498--
如果您已經有權訪問base64編碼圖像,爲什麼不將base64數據發送到服務器並將其解碼爲服務器端?這似乎會簡化你的客戶端JavaScript代碼? – 2011-04-25 23:04:58
我無法控制遠程服務器@Chris。 – Gajus 2011-04-26 11:43:39
如果圖像已經進行了base64編碼,則應該將該部分的Content-Transfer-Encoding字段設置爲base64。如果服務器端知道如何正確解析多部分/表單數據的帖子,它應該在將數據傳遞給應用程序代碼之前,將部分正確地解碼爲其二進制形式。 – ewh 2011-04-26 13:58:05