新的Flex2.0類(lèi)庫(kù)里提供了文件類(lèi),方便了上傳/下載文件。下面的程序demo演示了Flex2.0生成flash來(lái)訪(fǎng)問(wèn)本地文件,在flash里上傳用戶(hù)選擇的文件到服務(wù)器,flash客戶(hù)端可以處理文件上傳進(jìn)度等多個(gè)事件,服務(wù)器端是C#寫(xiě)的文件接收模塊,把用戶(hù)上傳的文件保存在服務(wù)器上。
Demo演示了ProgressEvent.PROGRESS, Event.SELECT 2個(gè)事件的處理方法。
順便提一下關(guān)于JSP的接收Flex上傳文件的方法(很多網(wǎng)友問(wèn)過(guò)這個(gè)問(wèn)題),我建議使用Jakarta Commons FileUpload的文件上傳組件,詳見(jiàn):http://jakarta./commons/fileupload/ !
測(cè)試效果:


測(cè)試環(huán)境:
操作系統(tǒng):windows2003 Server
Flex版本:Flex 2.0
Flash版本: flash Player 9
WEB服務(wù)器:
IIS 6.0
.net FrameWork 1.1
客戶(hù)端代碼:FileUpload.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="*" creationComplete="init();">
<mx:Script>
<
private var file: FileReference;
private function init(): void{
Security.allowDomain("*");
file = new FileReference();
file.addEventListener(ProgressEvent.PROGRESS, onProgress);
file.addEventListener(Event.SELECT, onSelect);
}
private function upload(): void{
file.browse();
}
private function onSelect(e: Event): void{
Alert.show("上傳 " + file.name + " (共 "+Math.round(file.size)+" 字節(jié))?",
"確認(rèn)上傳",
Alert.YES|Alert.NO,
null,
proceedWithUpload);
}
private function onProgress(e: ProgressEvent): void{
lbProgress.text = " 已上傳 " + e.bytesLoaded
+ " 字節(jié),共 " + e.bytesTotal + " 字節(jié)";
var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
bar.setProgress(proc, 100);
bar.label= "當(dāng)前進(jìn)度: " + " " + proc + "%";
}
private function proceedWithUpload(e: CloseEvent): void{
if (e.detail == Alert.YES){
var request: URLRequest = new URLRequest("http://localhost/JZService/WebForm1.aspx");
try {
file.upload(request);
} catch (error:Error) {
trace("上傳失敗");
}
}
}
]]>
</mx:Script>
<mx:Canvas width="100%" height="100%">
<mx:VBox width="100%" horizontalAlign="center">
<mx:Label id="lbProgress" text="上傳"/>
<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"
minimum="0" visible="true" maximum="100" label="當(dāng)前進(jìn)度: 0%"
direction="right" mode="manual" width="200"/>
<mx:Button label="上傳文件" click="upload();"/>
</mx:VBox>
</mx:Canvas>
</mx:Application>服務(wù)端代碼:WebForm1.aspx

private void Page_Load(object sender, EventArgs e)
{
// 在此處放置用戶(hù)代碼以初始化頁(yè)面
HttpFileCollection uploadedFiles = Request.Files;
string Path = Server.MapPath("data");
for(int i = 0 ; i < uploadedFiles.Count ; i++)
{
HttpPostedFile F = uploadedFiles[i];
if(uploadedFiles[i] != null && F.ContentLength > 0)
{
string newName = F.FileName.Substring(F.FileName.LastIndexOf("\\") + 1);
F.SaveAs(Path + "/" + newName);
}
}
}



