仿照网上“半杯咖啡”的文章,做了一下FLEX+JAVA的多个文件上传功能
半杯咖啡写的还是很好的,就是没全公开源码(不过主要代码已经给出了...).有些地方我还没弄懂:如进度条刷新... 效果如下:
界面就是仿照“半杯咖啡”的上传界面,加了TOOLTIP,位置没调。大小进行处理了,不过就是进度条没有处理好!删除一条数据时,再加入文件,位置不变的话进度条也不变!试了很多方法,就是没法改变。按照“半杯咖啡”的写法我这就报错,而且没看懂这代码什么意思:grid.parent.refresh(); 而且它是在itemrenderer里面,不好处理! 希望有高人指点一二。
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="486" height="316" title="文件上传" fontSize="12" borderColor="#CCECB7" backgroundColor="#A0D3B9" backgroundAlpha="0.8" status="此次共上传{selectedFiles.length}个文件">
<mx:Script>
<![CDATA[
import mx.MediaVO;
import mx.core.Application;
import mx.managers.PopUpManager;
import mx.collections.ArrayCollection;
import mx.controls.DataGrid;
import flash.net.FileReference;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
//声明上传用到的FileReferenceList
[Bindable]
private var fileL:FileReferenceList;
//声明上传文件用到的servlet(其实已经通过show方法传入)
[Bindable]
private var uploadUrl:String;
//选择文件时用到的arrayCollection,也是datagrid的数据源
[Bindable]
private var selectedFiles:ArrayCollection = new ArrayCollection;
//谁需要此组件的时候就调用此方法 UploadPanel.show("http://localhost:8082/Myflex/upload");
public static function show(uploadUrl:String = ""):void
{
var parentApp:Application = Application.application as Application;
var uv:UploadPanel = UploadPanel(PopUpManager.createPopUp(parentApp,UploadPanel,true));
uv.uploadUrl = uploadUrl;
PopUpManager.centerPopUp(uv);
}
//浏览文件
private function addFiles():void
{
fileL = new FileReferenceList();
fileL.addEventListener(Event.SELECT,selectFiles);
fileL.browse();
}
//选择文件到列表
private function selectFiles(event:Event):void
{
for(var i:int=0;i<event.currentTarget.fileList.length;i++){
var f:FileReference = FileReference(event.currentTarget.fileList[i]);
//obj是为了在datagird中显示将要上传的文件信息
var obj:Object= new Object();
obj.fileName = f.name;
obj.fileSize = formatFileSize(f.size);
obj.fileType = f.type;
obj.fileRefrence = f;
selectedFiles.addItem(obj);
}
}
//逐个上传文件
private function uploadHandler():void{
var file:FileReference;
for(var i:int = 0 ;i<selectedFiles.length;i++){
file = FileReference(selectedFiles[i].fileRefrence);
//media是将数据保存到数据库中声明的对象,不保存信息的话,这一段可以不要
var media:MediaVO = new MediaVO();
media.testid = this.parentApplication.tid;
media.mc = file.name;
media.size = formatFileSize(file.size);
media.attachment = "D:\\upload\\"+file.name;
this.parentApplication.aom2.mediaSvc.save(media);//由于remoteObject在别的窗口中,此句不必深究....
file.upload(new URLRequest(uploadUrl));
}
}
// 格式化文件大小
private function formatFileSize(numSize:Number):String {
var strReturn:String;
numSize = Number(numSize / 1000);
strReturn = String(numSize.toFixed(1) + " KB");
if (numSize > 1000) {
numSize = numSize / 1000;
strReturn = String(numSize.toFixed(1) + " MB");
if (numSize > 1000) {
numSize = numSize / 1000;
strReturn = String(numSize.toFixed(1) + " GB");
}
}
return strReturn;
}
//关闭本窗口
private function close():void
{
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>
<mx:DataGrid id="dg" dataProvider="{selectedFiles}" y="33" width="446" height="184" fontSize="10" horizontalCenter="0" textAlign="center" fontFamily="Verdana">
<mx:columns>
<mx:DataGridColumn headerText="文件名称" dataField="fileName" width="120" showDataTips="true"/>
<mx:DataGridColumn headerText="文件大小" dataField="fileSize" width="60"/>
<mx:DataGridColumn headerText="文件类型" dataField="fileType" width="50"/>
<mx:DataGridColumn headerText="上传状态" width="130">
<mx:itemRenderer>
<mx:Component>
<mx:HBox width="130" horizontalGap="2">
<mx:ProgressBar id="progress" width="100"
minimum="0" maximum="100" source="{data.fileRefrence}"
labelPlacement="center" progress="progress.label='%3%%';"
label="%3%%"
paddingLeft="2"
paddingRight="2">
</mx:ProgressBar>
<mx:LinkButton width="15" toolTip="取消上传" click="cancel()"
icon="@Embed('assets/cancel.png')" paddingLeft="2">
<mx:Script>
<![CDATA[
private function cancel():void{
data.fileRefrence.cancel();
progress.label = "已取消";
}
]]>
</mx:Script>
</mx:LinkButton>
<mx:LinkButton width="15" click="deleteItem(event)"
icon="@Embed('assets/delete.png')" toolTip="从列表中删除" paddingLeft="2">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.DataGrid;
private function deleteItem(event:MouseEvent):void {
var grid:Object = event.target.parent.parent.parent;
var dp:ArrayCollection = ArrayCollection(grid.dataProvider);
var index:int = dp.getItemIndex(data);
dp.removeItemAt(index);
progress.label = "0%";//刷新进度条的label
//grid.parent.refresh(); //这句在我机子上报错!哎... }
]]>
</mx:Script>
</mx:LinkButton>
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
<mx:Button x="199" y="233" label="浏览..." click="addFiles()"/>
<mx:Button x="289" y="233" label="上传" width="64" enabled="{selectedFiles.length>0}" click="uploadHandler()"/>
<mx:Button x="379" y="233" label="关闭" width="64" click="close()"/>
</mx:Panel>
相应的servlet代码如下:
package yang.utils; import javax.servlet.http.HttpServlet; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import java.util.List; import org.apache.commons.fileupload.FileUploadException; import java.util.Iterator; import org.apache.commons.fileupload.FileItem; import java.io.File; import java.io.UnsupportedEncodingException; import org.apache.commons.lang.ObjectUtils; public class FileUploadAction extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(FileUploadAction.class.getName()); private int maxPostSize = 100 * 1024 * 1024; private String uploadPath = "D:\\upload\\"; public FileUploadAction() { } //文件上传 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { logger("begin upload"); try { request.setCharacterEncoding("UTF-8");//防止文件名称带有汉字后传到服务器乱码 } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setContentType("text/html; charset=UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 4); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(maxPostSize); logger("request================"+ObjectUtils.toString(request)); List fileItems = null; try { fileItems = upload.parseRequest(request); logger("===================="+ObjectUtils.toString(fileItems)); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); log(item.toString()); if (!item.isFormField()) { String name = item.getName(); logger("file name = "+name); try { item.write(new File(uploadPath + name)); } catch (Exception ex) { logger(ex.getMessage()); } } } } catch (FileUploadException ex1) { logger("FileUploadException->"+ex1.getMessage()); } } private void logger(String info){ System.out.println(info); } }
不过不要忘了在web.xml中加入:
<!-- For file uploaded --> <servlet> <servlet-name>FileUploaded</servlet-name> <servlet-class>yang.utils.FileUploadAction</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploaded</servlet-name> <url-pattern>/FileUploaded</url-pattern> </servlet-mapping>
此处有两个上传组件可以参考:
http://labs.newmediateam.com/Multifileupload/FileUpload.html
http://weblog.cahlan.com/files/FileUpload/FileUploadApp.html