Flex文件上传下载


2009-07-28
Flex文件上传下载
博客分类:
Flex
FlexServletAdobe浏览器Apache
在Flex中,同样支持使用HTTP,multipart/form-data格式上传文件。还支持冲URL下载文件到本地,当然也可以直接跳转浏览器到下载链接,让下载工具来下。

一、文件上传:
分为Flex客户端,和Servlet服务器端。服务器端使用apache-common-filupload库上传。

客户端
Js代码
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[
import mx.controls.Alert;
//文件上传类
private var fileRefer:FileReference=new FileReference();
private function doUpload():void{
//添加事件
//用户选中文件后执行的事件
fileRefer.addEventListener(Event.SELECT,selectHandler);
//上传完成之后执行的事件
fileRefer.addEventListener(Event.COMPLETE,processResult);
fileRefer.addEventListener(ProgressEvent.PROGRESS, progress);
var filter:FileFilter = new FileFilter("Text", "*.mpg");
//打开选择文件对话框
var flag:Boolean=fileRefer.browse([filter]);
}
private function selectHandler(event:Event):void{
//根据URL执行文件上传,请求到后台Java的Servlet
var urlStr:String="http://localhost:8080/fileServer/FileUploadServlet";
var r:URLRequest=new URLRequest(urlStr);
fileRefer.upload(r);//第二个参数指定文件域的名字,默认为Filedata
//提交三个参数Filename,Filedata,Upload
}
private function processResult(event:Event):void{
Alert.show("上传成功!");
}

private function progress(event:ProgressEvent):void{
progressBar.setProgress(event.bytesLoaded, event.bytesTotal);
progressBar.label = "上传进度:" + int(event.bytesLoaded / event.bytesTotal * 100) + "%";
}

]]>
</mx:Script>

<mx:VBox horizontalCenter="0" verticalCenter="0">
<mx:Button label="上传文件" click="doUpload()" />
<mx:ProgressBar id="progressBar" labelPlacement="bottom" themeColor="#F20D7A"
minimum="0" visible="true" maximum="100" label="上传进度:0%"
direction="right" mode="manual" width="100"/>
</mx:VBox>
</mx:Application>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[
import mx.controls.Alert;
//文件上传类
private var fileRefer:FileReference=new FileReference();
private function doUpload():void{
//添加事件
//用户选中文件后执行的事件
fileRefer.addEventListener(Event.SELECT,selectHandler);
//上传完成之后执行的事件
fileRefer.addEventListener(Event.COMPLETE,processResult);
fileRefer.addEventListener(ProgressEvent.PROGRESS, progress);
var filter:FileFilter = new FileFilter("Text", "*.mpg");
//打开选择文件对话框
var flag:Boolean=fileRefer.browse([filter]);
}
private function selectHandler(event:Event):void{
//根据URL执行文件上传,请求到后台Java的Servlet
var urlStr:String="http://localhost:8080/fileServer/FileUploadServlet";
var r:URLRequest=new URLRequest(urlStr);
fileRefer.upload(r);//第二个参数指定文件域的名字,默认为Filedata
//提交三个参数Filename,Filedata,Upload
}
private function processResult(event:Event):void{
Alert.show("上传成功!");
}

private function progress(event:ProgressEvent):void{
progressBar.setProgress(event.bytesLoaded, event.bytesTotal);
progressBar.label = "上传进度:" + int(event.bytesLoaded / event.bytesTotal * 100) + "%";
}

]]>
</mx:Script>

<mx:VBox horizontalCenter="0" verticalCenter="0">
<mx:Button label="上传文件" click="doUpload()" />
<mx:ProgressBar id="progressBar" labelPlacement="bottom" themeColor="#F20D7A"
minimum="0" visible="true" maximum="100" label="上传进度:0%"
direction="right" mode="manual" width="100"/>
</mx:VBox>
</mx:Application>

主要使用FileReference类,调用其Browse方法,弹出文件选择框,提示用户选择要长传的文件。还可以使用FileFilter设置上传文件过滤,browse方法接受一个文件过滤数组。监听Event.SELECT事件,用户选择文件后触发,调用upload方法向url上传文件。 Event.COMPLETE在文件上传完成后触发。通过监听ProgressEvent.PROGRESS,设置文件长传进度条。 progressBar.setProgress(event.bytesLoaded, event.bytesTotal)。bytesLoaded为已上传大小,bytesTotal为总大小。
上传文件的默认字段名为Filedata,可以通过upload方法的第二个参数指定。

Servlet服务器端
使用的apache-common-fileupload也比较常用,就不多说了。

Java代码
public class FileUploadServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setSizeMax(1024 * 1025 * 1024);

try {
List items = fileUpload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
System.out.println(name + ":" + value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
String path = getServletContext().getRealPath("/");
File uploadedFile = new File(path +
+ new Random().nextInt(Integer.MAX_VALUE) + "_"
+ fileName);
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}
}
public class FileUploadServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setSizeMax(1024 * 1025 * 1024);

try {
List items = fileUpload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
System.out.println(name + ":" + value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
String path = getServletContext().getRealPath("/");
File uploadedFile = new File(path +
+ new Random().nextInt(Integer.MAX_VALUE) + "_"
+ fileName);
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}
}

二、文件下载:
Servlet服务器端:
Java代码
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = "hello.txt";
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment;filename="
+ fileName);
byte[] data = "Hello,world!".getBytes(Charset.forName("GBK"));
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

}
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = "hello.txt";
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment;filename="
+ fileName);
byte[] data = "Hello,world!".getBytes(Charset.forName("GBK"));
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

}

下载了一个文件名为hello.txt的文件,内容为Hello,world!

Flex客户端:
Js代码
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[
import flash.net.navigateToURL;

private var downloadURL:URLRequest;
private var file:FileReference;


public function doDownload():void {
//方法一
navigateToURL(new URLRequest("http://localhost:8080/fileServer/FileDownloadServlet"), "_blank");

//方法二
/*
downloadURL = new URLRequest("http://localhost:8080/fileServer/FileDownloadServlet");
file = new FileReference();
configureListeners(file);
file.download(downloadURL);
*/
}

private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.CANCEL, cancelHandler);
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(Event.SELECT, selectHandler);
}

//............省略事件处理函数
]]>
</mx:Script>



<mx:VBox horizontalCenter="0" verticalCenter="0">
<mx:Button label="下载文件" click="doDownload()" />
</mx:VBox>
</mx:Application>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[
import flash.net.navigateToURL;

private var downloadURL:URLRequest;
private var file:FileReference;


public function doDownload():void {
//方法一
navigateToURL(new URLRequest("http://localhost:8080/fileServer/FileDownloadServlet"), "_blank");

//方法二
/*
downloadURL = new URLRequest("http://localhost:8080/fileServer/FileDownloadServlet");
file = new FileReference();
configureListeners(file);
file.download(downloadURL);
*/
}

private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.CANCEL, cancelHandler);
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(Event.SELECT, selectHandler);
}

//............省略事件处理函数
]]>
</mx:Script>

<mx:VBox horizontalCenter="0" verticalCenter="0">
<mx:Button label="下载文件" click="doDownload()" />
</mx:VBox>
</mx:Application>

下载文件使用了两种方法

方法一最简单,直接跳转到下载链接(迅雷应该启动了)。
方法二同样使用FileReference,调用download方法,弹出对话框让用户选择下载的文件名。方法二有一个麻烦的地方就是,这里的默认文件名是FileDownloadServlet,因为其在下载前就弹出对话框让用户选择下载文件的存放路径,所以无法解析http头中的Content- disposition或filename信息,只有使用其他方式从服务器端取得默认文件名,比较麻烦。

原文地址:https://www.cnblogs.com/zdcaolei/p/2405308.html