php - 使用 Flex 和 PHP 上传图片

标签 php apache-flex image upload

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

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

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

最佳答案

这将是一个漫长的...

所以!步骤是:

  1. 打开一个浏览窗口。
  2. 监听用户选择文件
  3. 将所选文件实例化为变量
  4. 等待上传命令。
  5. 监听进度以便能够提供有关上传进度的视觉反馈(可选)。
  6. 收听完整的事件。
  7. 监听数据完成事件。 完成。

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
//----------------------------------------------------------

关于php - 使用 Flex 和 PHP 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3125094/

相关文章:

apache-flex - 如何将 maven 依赖项添加到 Flex Builder 3 中的 flex 构建路径?

image - 如何在 pubspec.yaml 中有效地处理图像作为 Assets ?

php正则表达式来分割字符串

php - Laravel 中共享组件包中的配置文件

php - 如何在 Laravel 4 中设置任务调度?

apache-flex - actionscript flex,如何将浏览器宽度发送到 swf 本身

php - 需要获得最接近的最小值和最大值

apache-flex - 覆盖 Object.toString 错误

c# - 调整许多位图大小时出现内存不足异常

image - 将图像放置在屏幕上的算法 "nicely"