`

使用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 与服务器交互

    在ActionScript 3 (AS3)中,与...通过灵活地使用这些类,你可以实现诸如获取数据、提交表单、上传文件等各种网络操作。在实际开发中,应结合具体需求,考虑性能优化、错误处理和安全措施,确保应用的稳定性和用户体验。

    Flex 向 java服务器 上传文件

    文件上传是通过调用FileReference的upload()方法完成的,该方法接受一个URLRequest对象,其中包含服务器端处理文件上传的URL。 在Java服务器端,我们需要一个接收并处理文件上传的控制器。Spring MVC是一个常用的...

    flex实现多文件上传

    在Flex中实现多文件上传,通常涉及到ActionScript编程、组件使用以及与服务器端的交互。下面将详细介绍如何使用Flex来实现这个功能。 一、Flex中的文件选择组件 在Flex中,我们可以使用`FileReference`类来处理文件...

    Flex上传文件与下载

    - 使用`upload`方法将文件发送到服务器端指定的Servlet进行处理。 - 在上传过程中监听进度事件并更新进度条。 #### 三、文件下载功能 虽然提供的代码片段中并未明确展示文件下载的具体实现细节,但可以推测其实现...

    swift 原生文件、图片上传

    本篇文章将深入探讨如何使用Swift进行原生文件和图片的上传,以及涉及的网络请求。 首先,我们要理解Swift中的文件操作。Swift提供了URL类型来表示文件路径,我们可以使用`FileManager`类来读取、写入和管理文件。...

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

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

    flashair本地文件上传

    4. **开始上传**:当用户选择文件后,调用FileReference的upload()方法,传入一个URLRequest对象,该对象的URL属性应指向服务器端处理文件上传的接口,method属性设为"POST"。同时,设置requestHeader "Content-Type...

    使用FLEX进行多文件上传和自定义上传信息.zip_flex_文件上传

    - Flex的`FileReference`类提供了`upload()`方法用于启动文件上传,并可以监听`progress`事件来获取上传进度。 - 当`progress`事件触发时,可以访问`event.bytesLoaded`和`event.bytesTotal`属性,计算并显示当前...

    flex 上传文件代码

    - 分块上传:使用SWFUpload或Plupload等第三方库,它们支持分块上传,能够处理大文件。 - 服务器端配置:如果使用的是PHP,可以修改php.ini中的`post_max_size`和`upload_max_filesize`设置;对于其他服务器环境,...

    flex4.5.1+.net4.0 单个文件上传

    在前端,当用户选择文件后,`FileReference`的`upload()`方法会被调用,传入一个`URLRequest`对象,该对象指向后端处理文件上传的URL。为了显示上传进度,可以监听`progress`事件,它会不断触发,每次携带当前已上传...

    完整的文件上传功能。File Reference实现

    其中,`urlRequest`是`URLRequest`对象,包含了文件上传的目标URL以及POST请求的数据。 **2. 多文件上传** 对于多文件上传,虽然`FileReferenceList`可以一次选择多个文件,但`FileReference`类一次只能处理一个...

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

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

    flex3 java 文件上传源码

    在这个“flex3 java 文件上传源码”中,我们有两个主要部分:Flex端(Upload)和Java端(UpLoadServer),它们分别负责用户的界面交互和后台的数据处理。 Flex3是一个基于ActionScript3的富互联网应用程序框架,...

    flex文件上传下载

    2. 浏览器下载:另一种方式是创建一个指向下载链接的 `URLRequest`,然后使用 `navigateToURL()` 函数,这会触发浏览器的默认下载行为,让用户使用浏览器内置的下载管理器来下载文件。 总结,Flex 文件上传下载功能...

    flex 多文件上传

    "flex 多文件上传"是指使用Adobe Flex框架实现的能够同时上传多个文件的功能。Flex是一款强大的RIA(富互联网应用)开发工具,它基于ActionScript编程语言和Flash Player运行时环境,提供丰富的用户界面组件和交互...

    flex 文件上传

    本文将详细介绍如何使用Flex进行文件上传,并通过一个具体的示例来演示其实现过程。 #### 二、核心组件:`FileReference` 在Flex中,`FileReference`类是用于处理文件上传的核心组件。它可以捕获用户选择的文件,...

    flex3+java文件上传

    4. **发起上传**:使用FileReference的upload()方法,传入一个URLRequest对象,指定文件上传的目标URL。URLRequest对象还可以设置POST或PUT方法,以及其他HTTP参数。 5. **监听上传进度**:可以监听FileReference的...

    Flex文件的上传下载.pdf

    在使用`FileReference`类进行文件上传时,需要注意的是,由于Flash Player的安全限制,无法直接获取到所选文件的完整路径信息。这意味着开发者只能获取文件的大小、创建日期等基本信息,而无法直接访问文件的具体...

Global site tag (gtag.js) - Google Analytics