Comments 22
> Здесь есть ещё одна тонкость: при загрузке на сервер с помощью FileReference почему-то не передаются куки(В URLLoader, кстати, все передается).
На самом деле куки передаются, но всегда из IE — это известная «особенность» объекта FileReference.
В терминах сильверлайт FileReference использует ClientHttpStack, а URLRequest использует BrowserHttpStack.
Также, нелишне было бы упомянуть, что URLRequest не предоставляет событий прогресса загрузки, поэтому загрузка миниатюр будет проходить две унылые стадии: начало и окончание.
На самом деле куки передаются, но всегда из IE — это известная «особенность» объекта FileReference.
В терминах сильверлайт FileReference использует ClientHttpStack, а URLRequest использует BrowserHttpStack.
Также, нелишне было бы упомянуть, что URLRequest не предоставляет событий прогресса загрузки, поэтому загрузка миниатюр будет проходить две унылые стадии: начало и окончание.
А какой версии ActionScript вы использовали? Я ценитель Flash MX 2004, там AS2, сработает ли или пытаться даже не стоит? :)
Ого :) А я ценитель Fireworks MX 2004 :)
Много нас таких осталось?
Много нас таких осталось?
Вам наверно и так известно, поэтому не стоит говорить о том, что AS3 быстрее чем AS2, да и удобнее, в конце концов.
AS2 я касался, но будет ли работать — не знаю. Я писал на AS3 под 10-й плеер.
В AS2 насколько я помню нет метода FileReference.load поэтому не получится делать ресайз на клиенте.
Как-то тоже довелось делать загрузку изображений из флеша на сервер с помощью multipart binary.
Правда заголовок нашаманил наш server-side программер. Для коллекции закину сюда, может кому-то пригодиться:
Правда заголовок нашаманил наш server-side программер. Для коллекции закину сюда, может кому-то пригодиться:
public function sendImage(bmpData:BitmapData, url:String):void
{
//Converting BitmapData into a PNG-encoded ByteArray
var imageBytes: ByteArray = PNGEncoder.encode(bmpData);
imageBytes.position = 0;
var boundary: String = '---------------------------7d76d1b56035e';
var header1: String = '--'+boundary + '\r\n'
+'Content-Disposition: form-data; name="poster"\r\n\r\n'
+'picture.jpg\r\n'
+'--'+boundary + '\r\n'
+'Content-Disposition: form-data; name="poster"; filename="picture.png"\r\n'
+'Content-Type: application/octet-stream\r\n\r\n';
//In a normal POST header, you'd find the image data here
var header2: String = '--'+boundary + '\r\n'
+'Content-Disposition: form-data; name="Upload"\r\n\r\n'
+'Submit Query\r\n'
+'--' + boundary + '--';
//Encoding the two string parts of the header
var headerBytes1: ByteArray = new ByteArray();
headerBytes1.writeMultiByte(header1, "ascii");
var headerBytes2: ByteArray = new ByteArray();
headerBytes2.writeMultiByte(header2, "ascii");
//Creating one final ByteArray
var sendBytes: ByteArray = new ByteArray();
sendBytes.writeBytes(headerBytes1, 0, headerBytes1.length);
sendBytes.writeBytes(imageBytes, 0, imageBytes.length);
sendBytes.writeBytes(headerBytes2, 0, headerBytes2.length);
var request: URLRequest = new URLRequest(url);
request.data = sendBytes;
request.method = URLRequestMethod.POST;
request.contentType = "multipart/form-data; boundary=" + boundary;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, uploadComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
try {
loader.load(request);
} catch (error: Error) {
trace("Unable to load requested document.");
}
}
try {
loader.load(request);
} catch (error: Error) {
trace("Unable to load requested document.");
}
}
Этот просто шикарно. Ставить в try-catch то, что никогда не выкинет исключения.
Читайте доки на UrlLoader.load:
Throws
ArgumentError — URLRequest.requestHeader objects may not contain certain prohibited HTTP request headers. For more information, see the URLRequestHeader class description.
MemoryError — This error can occur for the following reasons: 1) Flash Player or AIR cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to load() is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player or AIR cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to load is set to perform a POST operation.
SecurityError — Local untrusted files may not communicate with the Internet. This may be worked around by reclassifying this file as local-with-networking or trusted.
SecurityError — You are trying to connect to a commonly reserved port. For a complete list of blocked ports, see «Restricting Networking APIs» in the ActionScript 3.0 Developer's Guide.
TypeError — The value of the request parameter or the URLRequest.url property of the URLRequest object passed are null.
Throws
ArgumentError — URLRequest.requestHeader objects may not contain certain prohibited HTTP request headers. For more information, see the URLRequestHeader class description.
MemoryError — This error can occur for the following reasons: 1) Flash Player or AIR cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to load() is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player or AIR cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to load is set to perform a POST operation.
SecurityError — Local untrusted files may not communicate with the Internet. This may be worked around by reclassifying this file as local-with-networking or trusted.
SecurityError — You are trying to connect to a commonly reserved port. For a complete list of blocked ports, see «Restricting Networking APIs» in the ActionScript 3.0 Developer's Guide.
TypeError — The value of the request parameter or the URLRequest.url property of the URLRequest object passed are null.
Не надо вызывать Click() для инпута, его просто увеличивают, делают 100% прозрачным и позиционируют поверх красивой кнопки — этакий кликджекинг.
Еще подвох — если вы используете мультиинпут для файлов, то Опера (в отличие от FF и Chrome) посылает несколько файлов одним полем в соответствии со стандартом w3c, в результате PHP эти файлы не распознает (надо руками парсить входные данные). Проще запретить мультизагрузку в Опере, чем заморачиваться.
Еще подвох — если вы используете мультиинпут для файлов, то Опера (в отличие от FF и Chrome) посылает несколько файлов одним полем в соответствии со стандартом w3c, в результате PHP эти файлы не распознает (надо руками парсить входные данные). Проще запретить мультизагрузку в Опере, чем заморачиваться.
Есть отличный плагин для jQuery. Достаточно гибко настраивается и работает на всех браузерах
Для загрузки ByteArray рекомендую MultipartURLLoader.as
Мне нравится Plupload
Sign up to leave a comment.
Опыт создания загрузчика изображений