`

使用URLRequest上传文件 upload files using URLRequest

阅读更多

原文地址:http://www.pavlasek.sk/devel/?p=10

 

In Flash player it was possible until version 10 to upload files only by FileReference.upload method (there were some ugly hacks – such as uploading in external iframe).

Uploading files using directly FileReference.upload has some serious problems problems. Especially on Firefox, Flash player plugin creates it’s own request (different UserAgent, session and so) so on server it is handled in different session. All the parameters has to be sent, or some hacks has to be done (I manually set the jsessionid to each request).

And after all known hacks, it has still some serious problems using SSL – if the certificate is not validly imported to client machine, it just crashes without asking, if it has to trust it and so. See bugs:

Since v. 10 (and Flex 4), there is possibility to read local files directly, so I decided to try to upload files not using FileReference.upload method. But to read data as ByteArray and send it as POST request to server.

I found interesting class -UploadPostHelper in this article . Next I merged that example with my old code – browse for file and changed the method from FileReference.upload to FileReference.load . Server is java servlet using apache commons FileUpload – saves file to temp folder and sends XML response – all form items from post request and file uploaded – name and absolute path.

Adobe has changed security in flash player 10, it is impossible to send files in background (probably all requests now needs user interaction). It has to be in some user-action (click…) event handler, so I have two buttons, one for browse for a file, one for upload. Using just method that handles Event.COMPLETE (FileReference) causes Security sandbox violation .



Here is my Client code (UploadTest.mxml):

 

import mx.controls.Alert;

static public const SERVER_URL:String = "http://localhost:8081/flash10upload/servlet/FlexUpload";

private var fileReference:FileReference = new FileReference();

private function onLoad():void {
fileReference = new FileReference();
var myFilter:FileFilter = new FileFilter("Text","*.txt");
fileReference.browse([myFilter]);
fileReference.addEventListener(Event.SELECT,onFileSelect);
fileReference.addEventListener(Event.COMPLETE,onFileComplete);
}

private function onFileSelect(event:Event):void {
fileReference.load();
}

private function onFileComplete(event:Event):void {
Alert.show("File Loaded, click upload...");
uploadBtn.enabled = true;
}

private function upload():void {
var byteArray:ByteArray = new ByteArray();
var fileName:String = fileReference.name;
var uploadPath:String = SERVER_URL;
var parameters:Object = new Object();
parameters.test = "test1";

fileReference.data.readBytes(byteArray,0,fileReference.data.length);

var urlRequest:URLRequest = new URLRequest();
urlRequest.url = uploadPath;
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData(fileName, byteArray, parameters);
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );

var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
urlLoader.load(urlRequest);
}

private function onComplete(eventObj:Event):void {
var ldr:URLLoader = eventObj.currentTarget as URLLoader;

Alert.show(ldr.data , "complete");
}

private function onError(eventObj:ErrorEvent):void {
Alert.show("onError");
}
 




Here is my Server code (FlexUploadServlet):

package sk.pavlasek.flash10Upload.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class FlexUploadServlet extends HttpServlet {

private static final long serialVersionUID = 4588660828164350807L;

private static final Logger log = Logger.getLogger(FlexUploadServlet.class);

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws UnsupportedEncodingException {
res.setDateHeader("Expires", -1);
res.setDateHeader("Last-Modified", System.currentTimeMillis());
res.setHeader("Pragma", "");
res.setHeader("Cache-Control", "");

req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");

File disk = null;
FileItemFactory factory = new DiskFileItemFactory();
List items = null;
ServletFileUpload upload = new ServletFileUpload(factory);
ServletOutputStream out = null;

try {
res.setContentType("text/xml");
out = res.getOutputStream();
out.println("");

items = upload.parseRequest(req);
for (FileItem item : items) {

if (item.isFormField()) {
out.println(" + "\" value=\"" + item.getString() + "\" />");
} else {
String tempdir = System.getProperty("java.io.tmpdir");

if (!(tempdir.endsWith("/") || tempdir.endsWith("\\"))) {
tempdir = tempdir + System.getProperty("file.separator");
}

String fileName = tempdir + item.getName();
disk = new File(fileName);
item.write(disk);
log.debug(disk.getAbsolutePath());

out.println("");
out.println("" + item.getName()
+ "");
out.println("" + disk.getAbsolutePath() + "");
out.println("");
}
}
out.println("");
out.close();
} catch (FileUploadException fue) {
fue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
 
分享到:
评论

相关推荐

    AS3 中使用 URLRequest 和 URLLoader 与服务器交互

    AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 URLRequest 和 URLLoader 与服务器交互AS3 中使用 ...

    AS3中使用URLRequest和URLLoader 与服务器交互

    AS3 中使用 URLRequest 和 URLLoader 与服务器交互

    Flash结合PHP实现文件上传功能.rar

     upload.fla 文件中第一帧第代码第14行:urlRequest.url = "http://localhost/phpFlash/upload.php";  此路径改为您的本地环境配置路径,注意,路径一定要以http开头。    2.上传目录  upload.php 文件中第...

    PHP利用Flash文件上传图片(附FLA源文件).rar

     upload.fla 文件中第一帧第代码第14行:urlRequest.url = "http://localhost/phpFlash/upload.php";  此路径改为您的本地环境配置路径,注意,路径一定要以http开头。  2.上传目录  upload.php 文件中第二行...

    PHP+ Flash的文件上传程序(有Fla文件)

     upload.fla 文件中第一帧第代码第14行:urlRequest.url = "localhost/phpFlash/upload.php";  此路径改为您的本地环境配置路径,注意,路径一定要以http开头。    2.上传目录  upload.php 文件中第二行,$...

    ActionScript 3.0 与网络通信

    在ActionScript 3.0中,使用URLLoader和URLRequest类来加载外部文件。 加载成功的文件可使用特定类来访问数据,具体使用何类,取决于加载数据的数据类型。 1> 比如如果加载数据的格式为名称值对类型,则可以使用...

    Flash+Flex+Air移动开发入门经典 pdf

    第7章 使用文件系统 191 7.1 从文件系统读取 191 7.1.1 file和filestream类 192 7.1.2 创建files explorer app示例 195 7.2 修改文件和文件系统 207 7.3 利用浏览对话框 220 7.3.1 打开单个文件 220 7.3.2 ...

    flex通过URL获取request参数

    通过网页地址URL的参数传递。 例如:http://localhost:8080/text.mxml?myName=good&myValue=goods 在mxml里面获取到good同goods

    使用urllib库的urlretrieve()方法下载网络文件到本地的方法

    图片(文件)下载,核心方法是 urllib.urlrequest 模块的 urlretrieve()方法 urlretrieve(url, filename=None, reporthook=None, data=None) url: 文件url filename: 保存到本地时,使用的文件(路径)名称 reporthook...

    经典频谱文件

    import flash.net.URLRequest; import flash.utils.ByteArray; import flash.text.TextField; public class SoundMixer_computeSpectrum extends Sprite { public function SoundMixer_computeSpectrum() { ...

    以二进制形式读取外部图片文件(AIR)

    private var openItem:NativeMenuItem = new NativeMenuItem("打开文件"); private var quitItem:NativeMenuItem = new NativeMenuItem("退出"); private var helpMenu:NativeMenu = new NativeMenu; private ...

    CurlDSL:CurlDSL将cURL命令转换为URLRequest对象

    卷曲DSL 2019:copyright:杨卫中又名宗布尔 CurlDSL将cURL命令转换为URLRequest对象。 一旦有了Web API端点的cURL命令示例,Swift软件包就可以帮助您在iOS / macOS / tvOS中更轻松地构建HTTP客户端。 CurlDSL不会将...

    As3访问http和webService的类,HttpRequest

    var Request:URLRequest = new URLRequest(url); Request.method=method; Request.data = vars; trace(vars); loader = new URLLoader(Request); callBack = _returnMethod; loader....

    AS3读取XML

    简单的读取XML:加载部分var myXML:XML = new XML(); var XML_URL:String = "dat.xml";...var myXMLURL:URLRequest = new URLRequest(XML_URL); var myLoader:URLLoader = new URLLoader(myXMLURL);

    Download-Images-From-Web:从网络和系统上的 Storeaccess 数据文件下载图像

    从网络下载图像 从 Web 下载图像 步骤1.通过“NSURL”构造URL。 // Step1.... var imgURL = NSURL(string: ... let urlRequest = NSURLRequest(URL: imgURL!) 步骤 3. 异步执行请求以立即显示图像 // Step3. Exc

    flash as3 加载外部mp3

    //文本提示:动态文本框 ts_txt //"非你莫属.mp3 和fla在同一目录,如果不在同一目录要使用完整的绝对路径。 var s:Sound = new Sound() var req:URLRequest=new URLRequest("非你莫属.mp3")

    android 开发书籍 高清 PDF Developing Android Applications with Flex 4.5

    Learn how to read and write text files, browse the file system for media files, and create and write to an SQLite database Use the URLRequest class to open your app in the browser, place calls, and ...

    Alley:基本的“ URLSessionDataTask”微包装器,用于与HTTP(S)Web服务进行通信,并具有内置的自动请求重试功能

    为什么在大多数情况下,您需要从互联网上获取信息时,您可以: 希望无论您使用什么方式都可以在目标URL上获取数据如果根本不可能发生,请向最终客户显示一些有用的错误,并显示/记录实际发生的错误,以便您进行故障...

    声明式HTTP联网,专为SwiftUI设计-Swift开发

    安装-入门-生成请求-可编码-如何工作-请求组-请求链-Json-贡献-许可证与SwiftUI一起使用安装swift-request可以通过Swi安装进行安装-入门-构建请求-可编码-工作原理-请求组-请求链-Json-贡献-使用SwiftUI安装使用许可...

Global site tag (gtag.js) - Google Analytics