微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

YouTube是否通过URLRequest上传?

如何解决YouTube是否通过URLRequest上传?

| 我正在尝试通过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响应     

解决方法

        我刚刚遇到了一个非常类似的问题,终于得到了答案(对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,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]--
希望对您有所帮助!     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。