<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="334" height="140" fontSize="12" title="文件下载" creationComplete="init();">
<mx:states>
<mx:State name="Failure">
<mx:AddChild relativeTo="{FinishBtn}" position="before">
<mx:Button label="重试" id="RetryBtn" click="onRetry();"/>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
import mx.controls.Alert;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.events.ProgressEvent;
private var request:URLRequest;
private var _fileRef:FileReference;
private var _fileName:String;
private var _url:String;
private static const ROOT_URL:String="http://127.0.0.1:8080/TEST/";
private function init():void {
PopUpManager.centerPopUp(this);
}
public function set downUrl(uploadUrl:String):void {
_url=ROOT_URL + uploadUrl + ".action";
}
public function set fileName(fileName:String):void {
_fileName=fileName;
}
public function download():void {
Security.allowDomain("*");
_fileRef=new FileReference();
_fileRef.addEventListener(Event.COMPLETE, onComplete);
_fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
_fileRef.addEventListener(Event.CANCEL,onClose);
try {
request=new URLRequest(_url);
_fileRef.download(request, _fileName);
} catch (illegalOperation:IllegalOperationError) {
trace('IllegalOperationError');
onError();
} catch (security:SecurityError) {
trace('SecurityError');
onError();
}
}
private function onClose(evt:Event):void{
close(false);
}
private function onComplete(evt:Event):void {
this.currentState = '';
fileInfo.text="文件:" + _fileName + "下载完成!";
FinishBtn.label="完成";
}
// 进度条
private function onProgress(evt:ProgressEvent):void {
var loaded:uint = evt.bytesLoaded;
var total:uint = evt.bytesTotal;
fileInfo.text="文件:" + _fileName + " 大小:" + formatFileSize(total);
var proc:uint=loaded / total * 100;
pbar.setProgress(proc,100);
pbar.label="当前进度:" + proc + "%";
}
private function onError():void {
Alert.show('文件上传失败,请检查网络连接!', '错误', Alert.OK, null, function():void {
this.currentState = 'Failure';
fileInfo.text="文件:" + _fileName + "下载失败,请检查网络状态!";
});
}
private function onCancel():void {
_fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);
_fileRef.removeEventListener(Event.COMPLETE, onComplete);
_fileRef.cancel();
}
private function formatFileSize(size:Number):String {
if ((1024 * 1024 * 1024) <= size) {
return Math.round(size / (1024 * 1024 * 1024)) + "GB";
} else if ((1024 * 1024) <= size) {
return Math.round(size / (1024 * 1024)) + "MB";
} else if (1024 <= size) {
return Math.round(size / 1024) + "KB";
} else {
return size + "B";
}
}
private function close(flag:Boolean):void {
if (flag) {
try {
onCancel();
} catch (error:Error) {
trace("ERROR");
}
}
PopUpManager.removePopUp(this);
}
private function onRetry():void{
try {
_fileRef.download(request, _fileName);
} catch (illegalOperation:IllegalOperationError) {
trace('IllegalOperationError');
onError();
} catch (security:SecurityError) {
trace('SecurityError');
onError();
}
}
]]>
</mx:Script>
<mx:VBox height="100%" width="100%">
<mx:Label id="fileInfo" width="100%"/>
<mx:ProgressBar id="pbar" labelPlacement="center" minimum="0" maximum="100" label="下载进度: 0%" direction="right" mode="manual" width="100%"/>
<mx:HBox width="100%" verticalAlign="middle" horizontalAlign="center">
<mx:Button id="FinishBtn" label="终止" click="close(true);"/>
</mx:HBox>
</mx:VBox>
</mx:TitleWindow>
/**
*
*/
package com.io.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.ajax.base.action.BaseAction;
/**
* @author Merrygrass 2010-4-20
*
*/
@SuppressWarnings("serial")
public class DownloadAction extends BaseAction {
private String contentType;
private String fileName;
private InputStream inputStream;
private String contentLength;
public String download(){
return "download";
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getFilename() {
try {
fileName = "1005011041035572.flv";
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@SuppressWarnings("deprecation")
public InputStream getInputStream() throws Exception {
String realPath = ServletActionContext.getRequest().getRealPath("/upload");
File file = new File(realPath + "/" + "1005011041035572.flv");
if(file.exists()){
contentLength = String.valueOf(file.length());
}else{
throw new Exception("该文件不存在!");
}
inputStream = new FileInputStream(realPath + "/" + "1005011041035572.flv");
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getContentLength() {
return contentLength;
}
}
<action name="downloadAction" class="com.io.fileupload.DownloadAction">
<result name="download" type="stream">
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
<param name="contentLength">${contentLength}</param>
</result>
</action>