使用HTTPService在Flex中下载PDF文件

时间:2011-09-09 12:03:39

标签: flex flex4.5 httpservice


有人知道如何使用HTTPService下载pdf文件吗? 我这样做

private function downloadPDF():void
{
    var httpService:HTTPService = new HTTPService();
    httpService.url = "http://coenraets.org/flexandroid90/FlexAndroid90Minutes.pdf";
    httpService.addEventListener(ResultEvent.RESULT, result);
    httpService.addEventListener(FaultEvent.FAULT, fault);
    httpService.send();
}

private function fault(event:FaultEvent):void
{
    trace("Error");
    trace("\t> Code : "+event.fault.faultCode);
    trace("\t> Description : "+event.fault.faultString);
    trace("\t> Detail : "+event.fault.faultDetail);
}

private function result(event:ResultEvent):void
{
    var pdfFile:File = new File(File.applicationStorageDirectory.nativePath + File.separator + "myPDF.pdf");
    var fileStream:FileStream = new FileStream();
    fileStream.open(pdfFile, FileMode.WRITE);
    fileStream.writeUTFBytes(event.result as String);
    fileStream.close();
}

但我收到了错误

  

错误
  代码:Client.CouldNotDecode
  描述:错误#1090:XML解析器失败:元素格式错误   细节:null

使用URLLoader可以正常使用

private function initPDF():void
{
    loader = new downloadPDF();
    loader.dataFormat = URLLoaderDataFormat.BINARY;
    var request:URLRequest = new URLRequest("http://coenraets.org/flexandroid90/FlexAndroid90Minutes.pdf");
    configureListeners(loader);
    try {
        loader.load(request);
    } catch (error:Error) {
        trace("Unable to load requested URL.");
    }
}

private function configureListeners(dispatcher:EventDispatcher):void {
    dispatcher.addEventListener(Event.COMPLETE, completeHandler);
    dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}

private function completeHandler(event:Event):void {
    var pdfFile:File = new File(File.applicationStorageDirectory.nativePath + File.separator + "myPDF.pdf");
    var fileStream:FileStream = new FileStream();
    fileStream.open(pdfFile, FileMode.WRITE);
    fileStream.writeBytes(loader.data);
    fileStream.close();
}

private function ioErrorHandler(event:IOErrorEvent):void {
    trace("ioErrorHandler: " + event);
}

2 个答案:

答案 0 :(得分:1)

当然可以。

你只需要添加
httpService.resultFormat="text"

这只会给你字符串响应,而不会将其解析为xml。虽然不推荐使用,因为HTTPService适用于WebServices,但可以完成

答案 1 :(得分:-1)

问题是你无法使用HTTPLoader下载非文本或XML的内容(因此,它是文本)。