ファイルをアップロードするときは、常に FileReference オブジェクトの upload() メソッドを使用してきました。これは、要求で追加のパラメーターを渡しながら、Flash でファイルをアップロードする方法を示す簡単な ActionScript 3 アプリケーションです (これらは GET/クエリ文字列パラメーターとして渡されます:
package
{
import flash.display.Sprite;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class FileUploader extends Sprite
{
private var request:URLRequest;
private var file:FileReference;
public function FileUploader() {
var theText:TextField = new TextField();
theText.text = "Click here to select file!";
theText.autoSize = TextFieldAutoSize.CENTER;
this.addChild(theText);
theText.addEventListener(MouseEvent.CLICK, selectFile);
request = new URLRequest();
request.url = "http://192.168.178.75/upload/upload.php";
}
private function selectFile(evt:Event):void {
file = new FileReference();
configureListeners(file);
file.browse(getTypes());
}
public function uploadImage(file:FileReference):void {
var myData:URLVariables = new URLVariables();
myData.user = "valueOfUserParam";
myData.filename = file.name;
request.data = myData;
// "filedata": in PHP, the file can be accessed using $_FILE['filedata']
file.upload(request, "filedata");
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.CANCEL, cancelHandler);
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(Event.SELECT, selectHandler);
dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler);
}
private function getTypes():Array {
var allTypes:Array = new Array(getImageTypeFilter(), getTextTypeFilter());
return allTypes;
}
private function getImageTypeFilter():FileFilter {
return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
}
private function getTextTypeFilter():FileFilter {
return new FileFilter("Text Files (*.txt, *.rtf)", "*.txt;*.rtf");
}
private function cancelHandler(event:Event):void {
trace("cancelHandler: " + event);
}
private function completeHandler(event:Event):void {
trace("completeHandler: " + event);
}
private function uploadCompleteDataHandler(event:Event):void {
trace("uploadCompleteData: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
private function openHandler(event:Event):void {
trace("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
var file:FileReference = FileReference(event.target);
trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function selectHandler(event:Event):void {
var file:FileReference = FileReference(event.target);
trace("selectHandler: name=" + file.name + " URL=" + request.url);
this.uploadImage(file);
}
}
}
テストに使用したサーバー側の PHP コードは次のとおりです。
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = $_SERVER['DOCUMENT_ROOT']."/img/";
header("content-type: text/xml");
?><result>
<?php
if (empty($_FILES)) { ?>
<message>No file has been uploaded!</message>
<?php
} else {
$filename = $_FILES['filedata']['name'];
// Mark the file with a timestamp
$filename = str_replace(".jpg", time().".jpg", $filename);
$uploadfile = $uploaddir . $filename;
$success = move_uploaded_file($_FILES['filedata']['tmp_name'], $uploadfile);
if ($success) {
?>
<message>File is valid, and was successfully uploaded</message>
<debug>
<files><![CDATA[<?php print_r($_FILES); ?>]]></files>
<post><![CDATA[<?php print_r($_POST); ?>]]></post>
<get><![CDATA[<?php print_r($_GET); ?>]]></get>
</debug>
<?php
} else {
?>
<message>File upload failed miserably</message>
<?php
}
}
?>
</result>
PHP ファイルを Web サーバーのルート フォルダーに配置すると、画像がサブフォルダー img にアップロードされます。これは作成する必要があります。
デバッグ モードでのトレース出力は次のようになります。
selectHandler: name=Penny_test.jpg URL=http://localhost/upload/upload.php
openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]
progressHandler name=Penny_test.jpg bytesLoaded=11201 bytesTotal=11201
completeHandler: [Event type="complete" bubbles=false cancelable=false eventPhase=2]
uploadCompleteData: [DataEvent type="uploadCompleteData" bubbles=false cancelable=false eventPhase=2 data="<result>
<message>File is valid, and was successfully uploaded</message>
<debug>
<files><![CDATA[Array
(
[filedata] => Array
(
[name] => Penny_test.jpg
[type] => application/octet-stream
[tmp_name] => /tmp/phpaUurZr
[error] => 0
[size] => 11201
)
)
]]></files>
<post><![CDATA[Array
(
[Filename] => Penny_test.jpg
[Upload] => Submit Query
)
]]></post>
<get><![CDATA[Array
(
[filename] => Penny_test.jpg
[user] => valueOfUserParam
)
]]></get>
</debug>
</result>"]