2011-06-13 72 views
4

我試圖通過YouTube API上傳視頻。我可以驗證一切正常,並制定請求就好,但請求的正文與我遇到的二進制視頻數據有關。Youtube通過URLRequest上傳?

什麼是正確的方式來編碼文件數據並將其添加到urlRequest的主體?

我最好的猜測是:

public function getFileStreamBytes(fileName:String):String{ 

var byteArray:ByteArray = new ByteArray(); 
var returnString:String = ""; 

var file:File = new File(fileName); 
var fileStream:FileStream = new FileStream(); 
fileStream.open(file,FileMode.READ); 
fileStream.position = 0; 
fileStream.readBytes(byteArray); 

byteArray.position = 0; 
for(var i:Number = 0; byteArray.bytesAvailable > 0; i++){ 
    returnString += byteArray.readUTF(); 

} 
return returnString; 
} 

這將返回一個400錯誤的請求響應

+1

當您嘗試此操作時會發生什麼? – 2011-06-13 19:23:05

+0

發送您發送到服務器的標題信息。我們不能修復格式錯誤的頭文件,而不會看到頭文件 – 2011-06-13 21:44:21

+0

而在您發佈數據時,您只發布了獲取文件數據的代碼。 – 2011-06-13 21:45:28

回答

0

我只是遇到了一個非常類似的問題,終於得到了一個答案(信貸計算器用戶deadrunk)。事實證明,如果您通過URLRequest發送二進制數據,則必須手動將其格式化爲POST數據。看看下面的代碼:

//*** FORMAT POST DATA ***// 
var myByteArray:ByteArray = new ByteArray; //Data to be uploaded 
var myData:ByteArray = new ByteArray; 
var myBoundary:String = ""; 
var stringData:String; 
var i:uint; 

for (i = 0; i < 0x20; ++i) myBoundary += String.fromCharCode(uint(97+Math.random()*25)); 
myData.writeShort(0x2d2d); //-- 
myData.writeUTFBytes(myBoundary); 
myData.writeShort(0x0d0a); //\r\n 
stringData = 'Content-Disposition: form-data; name="fieldName"; filename="filename.txt"'; 
for (i = 0; i < stringData.length; i++) myData.writeByte(stringData.charCodeAt(i)); 
myData.writeShort(0x0d0a); //\r\n 
stringData = 'Content-Type: application/octet-stream'; //Change me! 
myData.writeShort(0x0d0a); //\r\n 
myData.writeShort(0x0d0a); //\r\n 
for (i = 0; i < stringData.length; i++) myData.writeByte(stringData.charCodeAt(i)); 
myData.writeBytes(myByteArray, 0, myByteArray.length); 
myData.writeShort(0x0d0a); //\r\n 
myData.writeShort(0x2d2d); //-- 
myData.writeUTFBytes(myBoundary); 
myData.writeShort(0x2d2d); //-- 

//*** SEND REQUEST ***// 
var uploadRequest:URLRequest = new URLRequest("http://127.0.0.1/upload.php"); 
uploadRequest.method = URLRequestMethod.POST; 
uploadRequest.contentType = 'multipart/form-data; boundary=' + myBoundary; 
uploadRequest.data = myData 
uploadRequest.requestHeaders.push(new URLRequestHeader('Cache-Control', 'no-cache')); 

var uploader:URLLoader = new URLLoader; 
uploader.dataFormat = URLLoaderDataFormat.BINARY; 
uploader.load(uploadRequest); 

基本上你添加一個「;邊界= [邊界線]」參數的內容類型,然後格式化您的要求,例如:

--[boundary string] 
Content-Disposition: form-data; name="[name of the form field]"; filename="[filename you want the server to see]" 
Content-Type: [ideally your data's actual content type] 

[your binary data] 
--[boundary string]-- 

我希望幫助!

相關問題