我正在尝试通过YouTube API上传视频。我可以对所有内容进行身份验证,并且可以很好地制定请求,但请求的主体与二进制视频数据有问题。
对文件数据进行编码并将其添加到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 Bad Request响应
答案 0 :(得分:0)
我刚刚遇到一个非常类似的问题,最后得到了一个答案(信用到stackoverflow用户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 = [boundary string]”参数,然后将请求格式化为:
--[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]--
我希望有所帮助!