1flex端
<mx:Button label="下 载" click="download()"/>
//下载
public function download():void{
var str:String=this.uploadfiles.selectedIndex.toString();
if(str=="-1"){
Alert.show("请选中要下载的文件");
}else{
downloadfiles();
}
}
public function downloadfiles():void{
var loadid:String=this.uploadfiles.selectedItem.loadid;
if(loadid==null || loadid==""){
Alert.show("对不起,该文件还未上传");
}
var urlAddress:String=model.root+"/uploadFiles.do?method=download&loadid="+loadid;
//URLRequest可以捕获单个HTTP的所有信息
var url:URLRequest=new URLRequest(urlAddress);
var loadname:String=this.uploadfiles.selectedItem.loadname;
//download()方法提示用户提供文件的保存位置并开始从远程 URL 进行下载。
filedown.download(url,loadname);
}
protected override function createChildren():void{
super.createChildren();
filedown.addEventListener(Event.COMPLETE,onDownCompleted);
}
public function onDownCompleted(evt:Event):void{
this.resultlabel.visible=true;
var fileref:FileReference = evt.currentTarget as FileReference;
resultlabel.text = "文件名:" + uploadfiles.selectedItem.loadname+ "下载完毕!";
}
java后台(action)
/**
* 文件下载
*
* @param mapping
* @param form
* @param request
* @param response
* @return
*/
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
log.info("Enter UploadFilesAction download===============");
// 被下载的文件id
String loadid = request.getParameter("loadid");
UploadFiles condition = this.uploadService.getFiles(loadid);
// 读取文件存放的目录
String filepath = this.getServlet().getServletContext().getRealPath("");
// 页面中的文件路径与服务器上的路径匹配(与服务器有关吗??)
// File file = new File(filepath, condition.getLoadpath());
File file = new File(condition.getLoadpath());
// 如果文件存在(读取文件流)
if (file.exists()) {
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Dispostion", "attachment;filename="
+ new String(condition.getLoadname().getBytes(),
"iso-8859-1"));
FileInputStream fis = new FileInputStream(file);
OutputStream ops = response.getOutputStream();
byte[] b = new byte[1024];
int real = fis.read(b);// 每次读取1024个字节
while (real > 0) {
ops.write(b, 0, real);
real = fis.read(b);
}
ops.close();
fis.close();
}
return null;
}