Youtube Upload via URLRequest?
I'm attempting to upload a video via the YouTube api. I can authenticate everything fine and formulate the request just fine but the body of the request with the binary video data I'm having an issue with.
What's the proper way to encode the file data and add it to the body of the urlRequest?
My best guess was:
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,FileMo开发者_如何学JAVAde.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
I just encountered a very similar problem, and finally got an answer (credit to stackoverflow user deadrunk). It turns out if you're sending binary data via a URLRequest, you have to manually format it as POST data. Have 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 a ";boundary=[boundary string]" parameter to the content type, 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's actual content type]
[your binary data]
--[boundary string]--
I hope that helps!
精彩评论