2006-07-29

FileReference 上傳圖檔

上傳圖檔後, 再載入該圖檔

為了避免中文檔名的影響,
上傳檔案的同時, 傳給後端一個 md5 編碼後的字串
並以該字串為上傳後的檔名

Frame Actions
import com.gsolo.encryption.MD5;

var uploadURL:String = "upload_uni_9.php";
var req:URLRequest = new URLRequest(uploadURL);
var myMD5:String;
var file:FileReference = new FileReference();

req.method = URLRequestMethod.POST;

// 按 upload_btn 選擇上傳的檔案upload_btn.addEventListener(MouseEvent.MOUSE_UP, myMouseUp);
function myMouseUp(e:Event):void{
file.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]);
}
//
file.addEventListener(Event.SELECT, myFileSelect);
file.addEventListener(Event.COMPLETE, myFileComplete);
// 選擇所欲上傳的圖檔後
function myFileSelect(e:Event):void{
var vars:URLVariables = new URLVariables();
myMD5 = MD5.encrypt(file.name+new Date().getTime());
vars.md5 = myMD5;
req.data = vars;
file.upload(req);
}
// 上傳完成後
function myFileComplete(e:Event):void{
var dotIndex:int = file.name.lastIndexOf(".");
var ext:String = file.name.substring(dotIndex);
var picURL:String = "./imgs/"+myMD5+ext;
// 載入圖片
var picReq:URLRequest = new URLRequest(picURL);
var pic:Loader = new Loader();
pic.load(picReq);
pic.x = 100;
pic.y = 100;
this.addChild(pic);
}

PHP
// 圖檔上傳後所欲存放的目錄
$up_dir = "./imgs/";
// 若目錄不存在, 則建立之
if(!is_dir($up_dir))
mkdir($up_dir, 0755);
// 取得上傳檔案的副檔名
$pos = strrpos($_FILES["Filedata"]["name"], ".");
if ($pos === false) {
$ext = "";
}else{
$ext = substr($_FILES["Filedata"]["name"], $pos);
}
// 以傳入的md5為儲存的檔名
$up_file = $up_dir . $_POST["md5"] . $ext;
// 將檔案放到設定的目錄內
move_uploaded_file($_FILES["Filedata"]["tmp_name"], $up_file);
chmod($up_file, 0777);

2006-07-26

將 ByteArray 物件傳給 PHP 存檔

ByteArray 物件可以透過 URLRequest 物件傳給後端
_btn.addEventListener(MouseEvent.MOUSE_UP, myMouseUp);
function myMouseUp(e:Event){
var req:URLRequest = new URLRequest("test_request.php");
req.data = byte_array_data;
req.method = URLRequestMethod.POST;
req.contentType = 'application/octet-stream';
flash.net.navigateToURL(req, "_blank");
}

若使用 PHP
$data = $GLOBALS['HTTP_RAW_POST_DATA'];
if (is_null($data)) {
echo "No data was sent";
} else {
$file = fopen("test.jpg", "w") or die("Can't open file");
if(!fwrite($file, $data)){
echo "Error writing to file";
}
print "OK\n";
fclose($file);
}

FB 留言