Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 3.0 (http://www.flasher.ru/forum/forumdisplay.php?f=83)
-   -   File upload без FileReference.upload (http://www.flasher.ru/forum/showthread.php?t=133743)

djtheme 11.12.2009 20:01

File upload без FileReference.upload
 
Здрасте уважаемые гуру Флеша.

Я создаю флеху, которая с помощью FileReference загружает файл-картинку пользователя с диска в себя. Потом делает манипуляции с ним (а именно меняет параметры картинки) и после этого я хочу загрузить измененный файл на сервер.

пробовал сделать так:

Код AS3:

                        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 - Работаеть на ура - проблема точно не в нем

ПАМАГИТЕ ПЛЗ!

zurkis 11.12.2009 20:09

Код AS3:

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 код:

<?php
move_uploaded_file
($_FILES['Filedata']['tmp_name'], 'uploads/'.$_FILES['Filedata']['name']);
?>


djtheme 11.12.2009 20:13

Спасибо - сейчас попробую!

Добавлено через 17 минут
Вы кажысь совсем мой пост не читали или читали невнимательно:

1. мне нужно с картинкой делать манипуляции, посему FileReference.upload не подходит - он аплоадит файл, который на диске.
2. Я не имею возможности создавать 2-ве кнопки. Есть только одна для FileReference.browse - без нее никак, а Аплоад запускаеца средствами JavaScrip - после верификации формы.

Цитата:

Сообщение от zurkis (Сообщение 872141)
Код AS3:

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 код:

<?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)?
НЕЛЬЗЯ!


Часовой пояс GMT +4, время: 10:53.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.