Просмотр полной версии : File upload без FileReference.upload
Здрасте уважаемые гуру Флеша.
Я создаю флеху, которая с помощью FileReference загружает файл-картинку пользователя с диска в себя. Потом делает манипуляции с ним (а именно меняет параметры картинки) и после этого я хочу загрузить измененный файл на сервер.
пробовал сделать так:
this.image = flash.display.Bitmap ( evt.target.content );
var btArray:ByteArray = new JPGEncoder(90).encode(this.image.bitmapData);
// set up the request & headers for the image upload;
var urlRequest : URLRequest = new URLRequest();
urlRequest.url = _path+'/reciveFile.php';
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData( _fileRef.name, btArray );
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
// create the image loader & send the image to the server;
var urlLoader : URLLoader = new URLLoader();
urlLoader.addEventListener(ProgressEvent.PROGRESS, eventFileUploadProgress);
urlLoader.addEventListener(Event.COMPLETE, eventFileUploadComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, eventFileUploadError);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, eventFileUploadError);
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load( urlRequest );
но скрипт до ходит до строчки urlLoader.load( urlRequest ); и потом выбрасывает ексепшн:
SecurityError: Error #2176: Определённые действия, например, те, после которых появляется всплывающее окно, могут быть только результатом взаимодействия с пользователем, к таким действиям относятся щелчок мышью или нажатие кнопки.
и ничего не отсылаеца!
Эксперименты показывают, что если закоментить строчку
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
то реквест отправляеца, но без файла канешна.
Я вызываю начало аплоада файла с JavaScript-а и не могу сделать это, как говорица в эксепшене, по нажатию кнопки в средине флеша. Кроме того без multipart/form-data реквест на сервер уходит и без нажатий на кнопки и т. п.
ЗЫ
UploadPostHelper - Работаеть на ура - проблема точно не в нем
ПАМАГИТЕ ПЛЗ!
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.*;
import flash.net.*;
import fl.controls.Button;
public class FileUpload extends Sprite {
private var _output:TextField;
private var _fileReference:FileReference;
var browseButton:Button = new Button();
var uploadButton:Button = new Button();
public function FileUpload() {
browseButton.move(10, 30);
browseButton.buttonMode = true;
browseButton.label = "Browse";
browseButton.addEventListener(MouseEvent.CLICK, browseHandler);
addChild(browseButton);
uploadButton.move(120,30);
uploadButton.buttonMode=true;
uploadButton.label ="Upload";
uploadButton.addEventListener(MouseEvent.CLICK, uploadHandler);
uploadButton.visible = false;
addChild(uploadButton);
_output = new TextField();
_output.width = 400;
_output.height = 400;
_output.y = 75;
addChild(_output);
_fileReference = new FileReference();
_fileReference.addEventListener(Event.SELECT, selectHandler);
_fileReference.addEventListener(Event.CANCEL, cancelHandler);
_fileReference.addEventListener(ProgressEvent.PROG RESS,progressHandler);
_fileReference.addEventListener(IOErrorEvent.IO_ER ROR,ioErrorHandler);
_fileReference.addEventListener(SecurityErrorEvent .SECURITY_ERROR,securityHandler);
_fileReference.addEventListener(Event.COMPLETE, completeHandler);
}
private function browseHandler(event:MouseEvent):void {
_fileReference.browse();
}
private function selectHandler(event:Event):void {
_output.text = "Selected File";
_output.appendText("\nName: " + _fileReference.name);
_output.appendText("\nSize: " + _fileReference.size);
_output.appendText("\nCreated On: " + _fileReference.creationDate);
_output.appendText("\nModified On: " +_fileReference.modificationDate);
uploadButton.visible = true;
}
private function cancelHandler(event:Event):void {
_output.text = "Canceled";
}
private function uploadHandler(event:MouseEvent):void {
_fileReference.upload(new URLRequest("simpleFileUpload.php"));
}
private function progressHandler(eventrogressEvent):void {
_output.text = "file uploading\noprogress (bytes): " + event.bytesLoaded + " / " + event.bytesTotal;
}
private function ioErrorHandler(event:IOErrorEvent):void {
_output.text = "an IO error occurred";
}
private function securityHandler(event:SecurityErrorEvent):void {
_output.text = "a security error occurred";
}
private function completeHandler(event:Event):void {
_output.text = "the file has uploaded";
uploadButton.visible = false;
}
}
}
ну и php
<?php
move_uploaded_file($_FILES['Filedata']['tmp_name'], 'uploads/'.$_FILES['Filedata']['name']);
?>
Спасибо - сейчас попробую!
Добавлено через 17 минут
Вы кажысь совсем мой пост не читали или читали невнимательно:
1. мне нужно с картинкой делать манипуляции, посему FileReference.upload не подходит - он аплоадит файл, который на диске.
2. Я не имею возможности создавать 2-ве кнопки. Есть только одна для FileReference.browse - без нее никак, а Аплоад запускаеца средствами JavaScrip - после верификации формы.
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.*;
import flash.net.*;
import fl.controls.Button;
public class FileUpload extends Sprite {
private var _output:TextField;
private var _fileReference:FileReference;
var browseButton:Button = new Button();
var uploadButton:Button = new Button();
public function FileUpload() {
browseButton.move(10, 30);
browseButton.buttonMode = true;
browseButton.label = "Browse";
browseButton.addEventListener(MouseEvent.CLICK, browseHandler);
addChild(browseButton);
uploadButton.move(120,30);
uploadButton.buttonMode=true;
uploadButton.label ="Upload";
uploadButton.addEventListener(MouseEvent.CLICK, uploadHandler);
uploadButton.visible = false;
addChild(uploadButton);
_output = new TextField();
_output.width = 400;
_output.height = 400;
_output.y = 75;
addChild(_output);
_fileReference = new FileReference();
_fileReference.addEventListener(Event.SELECT, selectHandler);
_fileReference.addEventListener(Event.CANCEL, cancelHandler);
_fileReference.addEventListener(ProgressEvent.PROG RESS,progressHandler);
_fileReference.addEventListener(IOErrorEvent.IO_ER ROR,ioErrorHandler);
_fileReference.addEventListener(SecurityErrorEvent .SECURITY_ERROR,securityHandler);
_fileReference.addEventListener(Event.COMPLETE, completeHandler);
}
private function browseHandler(event:MouseEvent):void {
_fileReference.browse();
}
private function selectHandler(event:Event):void {
_output.text = "Selected File";
_output.appendText("\nName: " + _fileReference.name);
_output.appendText("\nSize: " + _fileReference.size);
_output.appendText("\nCreated On: " + _fileReference.creationDate);
_output.appendText("\nModified On: " +_fileReference.modificationDate);
uploadButton.visible = true;
}
private function cancelHandler(event:Event):void {
_output.text = "Canceled";
}
private function uploadHandler(event:MouseEvent):void {
_fileReference.upload(new URLRequest("simpleFileUpload.php"));
}
private function progressHandler(eventrogressEvent):void {
_output.text = "file uploading\noprogress (bytes): " + event.bytesLoaded + " / " + event.bytesTotal;
}
private function ioErrorHandler(event:IOErrorEvent):void {
_output.text = "an IO error occurred";
}
private function securityHandler(event:SecurityErrorEvent):void {
_output.text = "a security error occurred";
}
private function completeHandler(event:Event):void {
_output.text = "the file has uploaded";
uploadButton.visible = false;
}
}
}
ну и php
<?php
move_uploaded_file($_FILES['Filedata']['tmp_name'], 'uploads/'.$_FILES['Filedata']['name']);
?>
Добавлено через 1 час 16 минут
В общем нашел тут в хелпах:
В приложении Flash Player 10 и более поздней версии при использовании типа содержимого multipart (например, multipart/form-data), в котором содержится отправка (обозначена параметром filename в заголовке content-disposition в теле оператора POST), к операции POST применяются правила безопасности для отправок:
* Операция POST должна быть выполнена в ответ на действие, инициированное пользователем, такое как щелчок мыши или нажатие клавиши.
* Если операция POST является междоменной (назначением операции POST не является сервер, на котором содержится SWF-файл, отправляющий запрос POST), целевой сервер должен предоставить файл политик URL, в котором разрешен междоменный доступ.
И кагбе вопрос переходит в другой - можно ли программно сгенерировать Клик мышкой или нажатие клавиши на клавиатуре - что бы было соответствующее Событие (Event)?
bicubic_bublic
12.12.2009, 02:06
Можно ли программно сгенерировать Клик мышкой или нажатие клавиши на клавиатуре - что бы было соответствующее Событие (Event)?
НЕЛЬЗЯ!
Работает на vBulletin ® версия 3.7.3. Copyright ©2000-2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Copyright © 1999-2008 Flasher.ru. All rights reserved.