Download Youtube via URLRequest?

I am trying to upload a video through the YouTube api. I can completely authenticate everything and formulate the request just fine, but the request body with binary video data, with which I had a problem.

What is the correct way to encode file data and add it to urlRequest body?

My best guess:

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; } 

This returns a 400 Bad Request response

+4
source share
1 answer

I ran into a very similar problem and finally got an answer (credit for the user stopoverflow user). It turns out that if you send binary data via URLRequest, you must manually format it as POST data. Take a look at this code:

 //*** 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); 

Basically you add the parameter "; border = [border string]" to the content type, and then format your request as such:

 --[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 actual content type] [your binary data] --[boundary string]-- 

I hope this helps!

0
source

All Articles