drvvvuyia15070493 2012-08-08 12:44
浏览 51
已采纳

使用URLLoader将文件从AS3写入PHP时的HttpStatus 0

I'm doing a project in AS3 where the user can design something and order it after. The design is exported to a PDF, PNG and XML. These files I want to save on the server. On MAMP it all works and I get the HTTPStatus 200, note that I run my SWF from MAMP but the php-script is successfully accessed on the remote server and the files are written to the Remote server with succes as well. However when i copy the SWF to the remote server, the files do not save and I get a HTTPStatus 0.

In the class that I use (see AS3 code below) I use a URLLoader to get to the following one line php script:

<?php file_put_contents($_POST['location'] . $_POST['fileName'], base64_decode($_POST['fileData']));

Here the AS3 class:

public class ServerConnection extends Sprite
{
    private var _files:Array = new Array();
    private var _fileNames:Array;
    private var _fileLocation:String = "";
    private var _scriptLocation:String;

    private var _fileSavesInProgress:Array = new Array();

    public function ServerConnection(scriptLocation:String = null, files:Array = null, fileNames:Array = null)
    {
        if (scriptLocation) setScriptLocation(scriptLocation);
        if (files) setFiles(files);
        if (fileNames) setFileNames(fileNames);
    }


    public function encodeFiles():void {
        for(var i:uint = 0; i < _files.length; i++) {
            _files[i] = encodeFile(_files[i]);
        }
    }
    public function encodeFile(byteArray:ByteArray):Base64Encoder {
        var base64:Base64Encoder = new Base64Encoder();
        base64.encodeBytes(byteArray);
        return base64;
    }

    public function saveFiles(location:String = null):void {
        if (location) setFileLocation(location);
        for(var i:uint = 0; i < _files.length; i++) {
            _files[i] = saveFile(_files[i], _fileNames[i]);
        }
    }
    public function saveFile(encodedFile:Base64Encoder, fileName:String = "test"):void {
        var data:URLVariables = new URLVariables();
        data.fileData = encodedFile;
        data.fileName = fileName;
        data.location = _fileLocation;
        this.dispatchEvent(new DebugEvent(DebugEvent.MESSAGE, "@serverConnection: a save file request was made for " + 
            fileName + "
" +
            "url: " + _fileLocation + "
" +
            " scriptLocation: " + _scriptLocation + "
"
        ));

        var request:URLRequest = new URLRequest(_scriptLocation);
        request.method = URLRequestMethod.POST;
        request.data = data;

        var loader:URLLoader= new URLLoader();
        loader.addEventListener(Event.COMPLETE, function(e:Event):void {fileSaved(loader);});
        loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatus);
        loader.addEventListener(IOErrorEvent.IO_ERROR, ioError);
        _fileSavesInProgress.push(loader);

        try {
            loader.load(request);
        } catch (e:*) {
            this.dispatchEvent(new DebugEvent(DebugEvent.MESSAGE, "@serverConnection: error:* = " + e + " 
"));
        }

        //navigateToURL(request);
    }

    public function displayObjectToPNG(displayObject:*, scale:Number = 1):ByteArray {
        var bmpData:BitmapData=new BitmapData(displayObject.width, displayObject.height, true, 0xFFFFFF);
        bmpData.draw(displayObject);

        var byteArray:ByteArray = PNGEncoder.encode(bmpData);
        return byteArray;
    }

    public function xmlToByteArray(xml:XML):ByteArray {
        var byteArray:ByteArray = new ByteArray();
        byteArray.writeUTFBytes(xml);
        return byteArray;
    }

    public function setScriptLocation(url:String):void {
        _scriptLocation = url;
    }

    public function setFileLocation(url:String):void {
        _fileLocation = url;
    }

    public function setFiles(array:Array, encode:Boolean = true):void {
        for each(var file:* in array) {
            for each(var type:XML in describeType(file).extendsClass.@type) { 
                if (type == "flash.display::DisplayObject") file = displayObjectToPNG(file);
            }
            if (typeof(file) == "xml") {
                file =  xmlToByteArray(file);
            }

            _files.push(file);
        }
        if (encode) encodeFiles();
    }

    public function setFileNames(array:Array):void {
        _fileNames = array;
    }


    // EVENTS
    private function httpStatus(e:HTTPStatusEvent):void {
        this.dispatchEvent(new DebugEvent(DebugEvent.MESSAGE, "@serverConnection: status = " + e.status + " 
"));
    }

    private function ioError(e:IOErrorEvent):void {
        this.dispatchEvent(new DebugEvent(DebugEvent.MESSAGE, "@serverConnection: IOErrorID = " + e.errorID + "  Message: "+ e.text + " 
"));
    }

    private function fileSaved(loader:URLLoader):void {
        this.dispatchEvent(new DebugEvent(DebugEvent.MESSAGE, "@serverConnection: file save completed. " + (_fileSavesInProgress.length -1) + " files to go 
"));
        _fileSavesInProgress.splice(_fileSavesInProgress.indexOf(loader), 1);

        if (_fileSavesInProgress.length == 0) {
            filesSaved();
        }
    }

    private function filesSaved():void {
        this.dispatchEvent(new DebugEvent(DebugEvent.MESSAGE, "@serverConnection: files saved 
"));
        this.dispatchEvent (new ClassAttributesLoaded(ClassAttributesLoaded.CLASS_ATTRIBUTES_LOADED));
    }

}

which I implement like this

    var s:ServerConnection = new ServerConnection(
    CONSTANT.SAVE_FILE_SCRIPT_LOCATION, 
    [currentTemplate.getXML(), exampleTemplate, pdf.save(Method.LOCAL)], 
    [CONSTANT.PACKAGE_ID + ".xml", CONSTANT.PACKAGE_ID + ".png", CONSTANT.PACKAGE_ID + ".pdf"]
);
s.addEventListener(DebugEvent.MESSAGE, writeToDebug);
s.addEventListener(ClassAttributesLoaded.CLASS_ATTRIBUTES_LOADED, exit);
s.saveFiles(CONSTANT.RELATIVE_FILE_DIRECTORY);

When I change loader.load(request); to navigateToURL(request); the code does work. on the local and remote server. for obvious reasons I can't use navigateToURL in this case. I do think that the fact that navigateToURL does work and loader.load(request) doesn't say something about the problem... but what?

I'm kind of stuck on this and would appreciate help. Thanks in advance!

PS: for testing I have set the permission of the remote DIR to 777. Furthermore the files are successfully saved from MAMP to Remote anyhow as stated before.

  • 写回答

1条回答 默认 最新

  • douqiang5163 2012-08-14 18:49
    关注

    Solution

    After long research I have found the solution: Adding the following crossdomain.xml to the root of my webserver (www.mysite.nl/).

    <?xml version="1.0" ?>
    
    <cross-domain-policy>
        <site-control permitted-cross-domain-policies="master-only"/>
        <allow-access-from domain="*.mydomain.com" to-ports="*"/>
        <allow-http-request-headers-from domain="*.mydomain.com" headers="*"/>
    </cross-domain-policy>
    

    This is not secure so if you want to use this solution please change 'mydomain.com' to the specific domain you want to allow. So that fixed it.

    How I got to the answer

    I was able to catch the error using the following code:

    loader.addEventListener(IOErrorEvent.IO_ERROR, handleSecurityError);
    

    The error returned was the following: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048"]

    Note that usually the error contains: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048: Security Sandbox Violation : http://www.domain-a.com/url/file-a.swf can not load data from http://www.domain-b.com/url/file-b.swf"]

    This error is usually solved by loading a security policy. check out this link about how to use security policies: http://kb2.adobe.com/cps/142/tn_14213.html

    However in this case the url accessed is within the same domain. (NOTE: same folder :D) So initially I thought this was irrelevant as there is no other domain contacted. But after searching for a week I got so desperate I tried it any how.

    So adding a crossdomain.xml to the root of my server solved the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)