使用Flex和PHP上传图片

我想知道是否有人知道使用Flex 4和PHP上传图像文件的最佳方法.我已经在网上搜索过,但是大多数都使用Flex 2或更旧的版本.我只是好奇是否有任何新方法可以做到这一点.如果您知道任何好的网站或文章,请回复.感谢您的帮助!

更新:
  刚刚在这里找到了一个不错的..

http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html

解决方法:

这将是一个漫长的…

所以!这些步骤是:

>打开浏览窗口.
>收听用户选择文件
>将所选文件实例化为变量
>等待上载命令.
>听取进度,以便能够提供有关上传进度的视觉反馈(可选).
>收听完整的事件.
>监听数据完成事件.
做完了

MXML代码(节选):

<!-- Will open the browse window. -->
<s:Button id="bttSelectFile" label="Select file" click="selectFile()"/>
<!-- Will validate and start the upload process. -->
<s:Button id="bttUpload" label="Upload file" click="upload()"/>
<!-- Shows upload progress after it starts. -->
<mx:ProgressBar id="progressBar" labelPlacement="center" label="0%" width="300" height="40"
   horizontalCenter="0" verticalCenter="0" alpha="0"
   minimum="0" maximum="100" indeterminate="false" mode="manual"/>

ActionScript部分:

//----------------------------------------------------------
//START of Part 1: Initialization and declarations stage
//----------------------------------------------------------

import mx.controls.Alert;

//If relative doesn't work, try absolute path. Might differ between localhost home setup and production server.
private const UPLOAD_URL:String='uploadFile.php';
private var fileReference:FileReference;

//Handler for the application or component (etc) initialize event.
private function init():void
{
   initializeFileReference();
}
//Instantiates fileReference variable and adds listeners.
private function initializeFileReference():void
{
   fileReference=new FileReference();
   fileReference.addEventListener(Event.SELECT,fileSelectHandler);//Dispatched when user selects a file from Dialog Box.
   fileReference.addEventListener(Event.CANCEL,fileCancelHandler);//Dispatched when user dismisses the Dialog Box.
   fileReference.addEventListener(HTTPStatusEvent.HTTP_STATUS,fileErrorHandler);//HTTP Error
   fileReference.addEventListener(IOErrorEvent.IO_ERROR,fileErrorHandler);//IO Error
   fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR,fileErrorHandler);//Security Sandbox Error
   fileReference.addEventListener(ProgressEvent.PROGRESS,fileProgressHandler);//Upload Progress
   fileReference.addEventListener(Event.COMPLETE,fileCompleteHandler);//Dispatches when the file upload operation completes successfully 
   fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,fileDataCompleteHandler);//Dispatched when data has been received from the server after a successful upload.
}
//Set fileReference to NULL and removes listeners.
private function killFileReference():void
{
   fileReference.removeEventListener(Event.SELECT,fileSelectHandler);
   fileReference.removeEventListener(Event.CANCEL,fileCancelHandler);
   fileReference.removeEventListener(HTTPStatusEvent.HTTP_STATUS,fileErrorHandler);
   fileReference.removeEventListener(IOErrorEvent.IO_ERROR,fileErrorHandler);
   fileReference.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,fileErrorHandler);
   fileReference.removeEventListener(ProgressEvent.PROGRESS,fileProgressHandler);
   fileReference.removeEventListener(Event.COMPLETE,fileCompleteHandler); 
   fileReference.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,fileDataCompleteHandler);
   fileReference=null;
}

//----------------------------------------------------------
//END of Part 1: Initialization and declarations stage
//----------------------------------------------------------


//----------------------------------------------------------
//START of Part 2: File Selection
//----------------------------------------------------------

//Called upon pressing the select file button (bttSelectFile click handler).
private function selectFile():void
{
   //Try to open the browse window.
   try
   {
      //I disable the browse button after it's been clicked, I will enable it later. [OPTIONAL]
      bttSelectFile.enabled=false;
      //Limit the files the user can select.
      fileReference.browse(getTypes());
   }
   catch(e:Error){bttSelectFile.enabled=true;Alert.show("Cannot browse for files.","Error");}
}
private function getTypes():Array
{
   //Return an array of selectable file extensions (not MIME Types).
   var allTypes:Array=new Array(getImageTypeFilter());
   return allTypes;
}
private function getImageTypeFilter():FileFilter
{
   //Limit selection to files with the jpg or jpeg extensions.
   return new FileFilter("Images(*.jpg, *.jpeg)","*.jpg;*.jpeg;");
}
//Called after file was selected.
private function fileSelectHandler(event:Event):void
{
   //Re-enable the bttSelectFile button in case the user wants to select a different file. [OPTIONAL]
   bttSelectFile.enabled=true;
   //Change the label of the button to match the select file name. [OPTIONAL]
   bttSelectFile.label=fileReference.name;
}
//Called if user dismisses the browse window (Cancel button, ESC key or Close option)
private function fileCancelHandler(event:Event):void
{
   //Enable the button so he is able to re-open the browse window. [OPTIONAL]
   bttSelectFile.enabled=true;
}
//----------------------------------------------------------
//END of Part 2: File Selection
//----------------------------------------------------------


//----------------------------------------------------------
//START of Part 3: File Upload
//----------------------------------------------------------

//Function to validate that a file was selected and eventually other fields in the form as well.
private function valid():Boolean
{
   var result:Boolean=true;
   if(fileReference==null)
   {
      result=false;
      //I set the errorString for the button. You can give user feedback anyway you want though.
      bttSelectFile.errorString='You have not selected a file.';
   }
   //Other validation criteria
   return result;
}
//Called after the upload button (bttUpload) is pressed.
private function upload():void
{
   if(valid())
   {
      //Disable the submit button to avoid multi-submit.
      bttSubmit.enabled=false;
      //Call the upload funcion.
      startUpload();
   }
}
//Starts the upload process.
private function startUpload():void
{
   try
   {
      //Try to upload. myPicture will be the name of the FILE variable in PHP, e.g. $_FILE['myPicture'].
      fileReference.upload(new URLRequest(UPLOAD_URL),"myPicture");
   }
   catch(e:Error)
   {
      //Zero-byte file error.
      Alert.show("Zero-byte file selected.","Error");
   }
}
//I hadle errors in this example with a single function.
//It's better to have a different function to handle each of the 3 possible errors.
//Security Sandbox, IOError or HTTPStatus
private function fileErrorHandler(event:Event):void
{
   Alert.show("File upload failed.","Error");
   //For debugging you should see the entire error dump.
   Alert.show(event.toString());
}
//Set ProgressBar progress to match upload progress
private function fileProgressHandler(event:ProgressEvent):void
{
   //Calculate percentage uploaded.
   var percentage:uint= Math.round(event.bytesLoaded*100/event.bytesTotal);
   //Set progressBar progress.
   progressBar.setProgress(percentage,100);
   //Update progressBar label.
   progressBar.label=percentage+'%';
}
//Called when file was sucessfully copied to the server.
//Upload not over yet though, PHP still has to confirm it did its part.
private function fileCompleteHandler(event:Event):void
{
   //Enable bttSelectFile. [OPTIONAL]
   bttSelectFile.enabled=true;
}
//Called when the PHP upload file specified in the UPLOAD_URL constant provides an "answer".
private function fileDataCompleteHandler(event:DataEvent):void
{
   //I print (or echo) a number in PHP based on what happened
   //3 = file is not JPG MIME Type check
   //0 = move_uploaded_file function failed
   //else = return the filename. I set PHP to rename the file and if all is good, it will return the name of the newly uploaded file.
   var response:String=event.data;
   if(response=='3'){Alert.show("Selected file is not a JPG.","Error");}
   else if(response=='0'){Alert.show("File upload failed.","Error");}
   else
   {
      //Do whatever you want, upload process completed successfully.
      //Maybe insert into database?
   }
}
//----------------------------------------------------------
//END of Part 3: File Upload
//----------------------------------------------------------

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

相关推荐