1354676695_3500
uploadgrid.mxm 上傳jar的類
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="HTTP://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
creationComplete="group_creationCompleteHandler(event)"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="500" height="250">
<s:layout>
<s:BasicLayout/>
</s:layout>
<fx:Declarations>
<mx:NumberFormatter id="filesizeFormatter" useThousandsSeparator="true"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.events.CollectionEvent;
import mx.events.FlexEvent;
import mx.formatters.CurrencyFormatter;
import mx.formatters.NumberFormatter;



[Bindable]
public var deleteenabled:Boolean=true;

 

//檔案清單
[Bindable]
private var fileRefs: FileReferenceList = new FileReferenceList();

 

//這個位址是我測試用的服務器位址
[Bindable]
private var urlrequest: URLRequest = new URLRequest("HTTP://localhost:8080/auto/FileUploaded");

 

//檔案清單中的檔
[Bindable]
public var selectedFiles: ArrayCollection = new ArrayCollection([]);

 

//上傳的檔
private var singleThreadFiles: Array = [];

 

//逐個上傳檔
private function singleThreadUploadFile(): void
{
//FIFO:逐個從清單中取出,進行上傳
if (singleThreadFiles.length > 0)
{
var mf: MyFile = singleThreadFiles.pop() as MyFile ;
var f:FileReference=mf.fr;
f.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, doSingleUploadFileComplete);
f.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
f.upload(urlrequest);
}
else
{
uploadbutton.enabled=false;
uploadtext.text="全部上傳成功!";
showuploadjar();

 

}
}

 

private function doSingleUploadFileComplete(event: Event): void
{
var f: FileReference = event.target as FileReference;
f.removeEventListener(Event.COMPLETE, doSingleUploadFileComplete);
singleThreadUploadFile();
}

 

//初始化
private function init(): void
{
Security.allowDomain("*");
fileRefs.addEventListener(Event.SELECT, fileSelectHandler);
fileRefs.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}

 

//要上傳的檔類型,我這裏是jar檔
private function selectFile(): void
{

 

var jarfile:FileFilter = new FileFilter("jar檔(*.jar)", "*.jar*");
var allfile:FileFilter = new FileFilter("所有檔(*.*)", "*.*");
var allTypes:Array = new Array();
allTypes.push(jarfile);
allTypes.push(allfile);
fileRefs.browse(allTypes);

 

}

 

//用戶選擇的檔,如果需要判斷是否可以多次選擇同名的檔可以在這裏判斷
private function fileSelectHandler(event: Event): void
{
for each (var f: FileReference in fileRefs.fileList)
{
var mf:MyFile = new MyFile(f);
selectedFiles.addItem(mf);
}
}

 

//出錯後的處理
private function ioErrorHandler(e:IOErrorEvent): void
{
Alert.show(e.text);
Alert.show("請檢查網絡或程式是否正常,請刪除上傳不成功的jar,重新選擇後上傳!");
selectFileButton.enabled=true;
cleanAll.enabled=true;
deleteenabled=true;
}

 

//刪除清單中的檔
public function removeFile(mf: MyFile): void
{
var index: int = selectedFiles.getItemIndex(mf);
if (index != -1)
selectedFiles.removeItemAt(index);
}

 

//初始化組件或應用程式
protected function group_creationCompleteHandler(event:FlexEvent):void
{
init();
}

 

//確認上傳的檔
protected function button1_clickHandler(event:MouseEvent):void
{
Alert.show("開始上傳後不能更改選擇的jar包 ,確定上傳?",
"確認上傳",
Alert.YES|Alert.NO,
null,
startUpload);
}

 

//根據業務的需求上傳後不能更改,可以根據自己的業務邏輯去改相應的處理
private function startUpload(e: CloseEvent): void{

 

if (e.detail == Alert.YES){
selectFileButton.enabled=false;
cleanAll.enabled=false;
deleteenabled=false;
singleThreadFiles = selectedFiles.toArray().concat();

 

for(var i:int=0;i<singleThreadFiles.length;i++)
{
if(singleThreadFiles[i] is MyFile)
{
var mf:MyFile= singleThreadFiles[i] as MyFile;
var f:FileReference=mf.fr;
trace(f.name);
}
}
singleThreadFiles.reverse();
singleThreadUploadFile();
}
}

 

//輸出上傳後的jar的資訊,如果需要更多的資訊可以在MyFlie類裏找到
private function showuploadjar():void
{
for(var i:int=0; i<selectedFiles.length;i++)
{
var mf:MyFile=selectedFiles.getItemAt(i) as MyFile;
// Alert.show(mf.uploadFilePath+mf.uploadFileName);
trace("上傳後的路徑:"+mf.uploadFilePath+mf.uploadFileName);
mf.removeDateEvent();
}
}

 

]]>
</fx:Script>
<s:VGroup paddingTop="10">
<mx:VBox>
<mx:HBox width="100%">
<mx:Button id="selectFileButton" label="瀏覽" click="selectFile()"/>
<mx:Box width="100%" horizontalAlign="right">
<mx:Button id="cleanAll" click="selectedFiles.removeAll();" label="清空"/>
</mx:Box>
</mx:HBox>
<mx:DataGrid id="files" dataProvider="{selectedFiles}" >
<mx:columns>
<mx:DataGridColumn width="200" headerText="檔案名" dataField="fr.name" />
<mx:DataGridColumn width="100" headerText="大小(字節)" dataField="fr.size">
<mx:itemRenderer>
<fx:Component>
<mx:Label text="{outerDocument.filesizeFormatter.format(data.size)}" textAlign="right"/>
</fx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn width="100" headerText="狀態" dataField="uploadlable" />
<mx:DataGridColumn headerText="刪除" width="80">
<mx:itemRenderer>
<fx:Component>
<mx:HBox fontSize="10" fontWeight="normal" fontThickness="1">
<fx:Script>
<![CDATA[
protected function linkbutton1_clickHandler(event:MouseEvent):void
{
var mf:MyFile = data as MyFile;
outerDocument.removeFile(mf);
}

]]>
</fx:Script>
<mx:LinkButton label="Delete" click="linkbutton1_clickHandler(event)" enabled="{outerDocument.deleteenabled}">
</mx:LinkButton>
</mx:HBox>
</fx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>

</mx:columns>
</mx:DataGrid>
<mx:HBox>
<mx:Button label="上傳" id="uploadbutton" click="button1_clickHandler(event)" />
<s:Label paddingTop="7" id="uploadtext" text="" />
</mx:HBox>
</mx:VBox>
</s:VGroup>
</s:Application>




自己封裝as類MyFile.as:用於存儲上傳後的資訊。


package outsideSys.windows
{
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.FileReference;


/**
* @author
* 描述:
* 創建時間:2012-12-4 下午2:01:56
*/
[Bindable]
public class MyFile
{


private var _uploadFileName:String;

private var _uploadFilePath:String;

private var _uploadIsSuceess:Boolean;

private var _uploadProgress:uint;

private var _uploadlable:String="等待上傳";

private var _fr:FileReference;

public function MyFile(f:FileReference)
{
super();
this.fr=f;
_fr.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadcomplete);
// _fr.addEventListener(ProgressEvent.PROGRESS,funcuploadProgress);
}

public function removeDateEvent():void
{
_fr.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadcomplete);
}


protected function uploadcomplete(event: DataEvent): void
{
//服務器端一定要返回數據,否則,這個方法就不起作用了
var uploadInfo:String=event.data;
var uploadInfoArray:Array = uploadInfo.split("#");
if(uploadInfoArray[0]=="true")
{
this.uploadIsSuceess=true;
this.uploadFilePath=uploadInfoArray[1];
this.uploadFileName=uploadInfoArray[2];
this.uploadlable=uploadInfoArray[3];
//trace(uploadlable);
trace(uploadFileName+"完成2");
}

}



// protected function funcuploadProgress(event: ProgressEvent): void
//        {
// this.uploadProgress = event.bytesLoaded / event.bytesTotal * 100;
//        }


public function get uploadlable():String
{
return _uploadlable;
}

public function set uploadlable(value:String):void
{
_uploadlable = value;
}

public function get fr():FileReference
{
return _fr;
}

public function set fr(value:FileReference):void
{
_fr = value;
}

public function get uploadProgress():uint
{
return _uploadProgress;
}

public function set uploadProgress(value:uint):void
{
_uploadProgress = value;
}

public function get uploadIsSuceess():Boolean
{
return _uploadIsSuceess;
}

public function set uploadIsSuceess(value:Boolean):void
{
_uploadIsSuceess = value;
}

public function get uploadFilePath():String
{
return _uploadFilePath;
}

public function set uploadFilePath(value:String):void
{
_uploadFilePath = value;
}

public function get uploadFileName():String
{
return _uploadFileName;
}

public function set uploadFileName(value:String):void
{
_uploadFileName = value;
 
}

public function get uploadIsSuceess():Boolean
{
return _uploadIsSuceess;
}

public function set uploadIsSuceess(value:Boolean):void
{
_uploadIsSuceess = value;
}

public function get uploadFilePath():String
{
return _uploadFilePath;
}

public function set uploadFilePath(value:String):void
{
_uploadFilePath = value;
}

public function get uploadFileName():String
{
return _uploadFileName;
}

public function set uploadFileName(value:String):void
{
_uploadFileName = value;
}

}
}


後台的java代碼FileUploaded.java:




package com.web.action;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.system.constants.PropertiesFile;
import com.system.util.PropertiesAnalysis;

//import com.system.constants.PropertiesFile;
//import com.system.util.PropertiesAnalysis;



/**
*
* @author crystal
*/
public class FileUploaded extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
// 定義檔的上傳路徑
// private String uploadPath = PropertiesAnalysis.findProperties(PropertiesFile.DEPLOYXONFIG, "jarpath");
private String uploadPath = "D://jarfile//";

// 限制檔的上傳大小
private int maxPostSize = 100 * 1024 * 1024;

public FileUploaded() {
super();
}

public void destroy() {
super.destroy();
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Access !");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();

//保存檔到服務器中
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date=sdf.format(new Date());
String jaruploadPath=uploadPath+date+"\\";
File file = new File(jaruploadPath);
//判斷檔夾是否存在,如果不存在則創建檔夾
if (!file.exists()) {
file.mkdir();
}
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String name = item.getName();
System.out.println(name);
String newname=name.split(".jar")[0]+new Date().getTime()+".jar";

try {
item.write(new File(jaruploadPath + newname));
//我輸出的格式:true|flase#檔路徑#檔案名#是否成功的資訊,用#號隔開的。
response.getWriter().write("true#"+jaruploadPath+"#"+newname+"#上傳成功。");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write("false#"+e.getMessage());
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
response.getWriter().write(e.getMessage());
System.out.println("false#"+e.getMessage() + "結束");
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}



web.xml中的xml設定檔:




<!-- flex 檔上傳 -->
<servlet>
<servlet-name>FileUploaded</servlet-name>
<servlet-class>com.web.action.FileUploaded</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileUploaded</servlet-name>
<url-pattern>/FileUploaded</url-pattern>
</servlet-mapping>
 

  

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()