多文件上传-flex版本
多文件上传和单文件上传后台处理方式是一样的,所以可以直接使用单文件上传的处理程序。
1.web.config
appSettings配置节
<add key="UploadFileUrl" value="http://file.mydomain.com/" />
<add key="UploadFilePath" value="E:\file.mydomain.com\uploadfile\"/>
2.asp.net文件接收保存处理程序
//UploadHandler.ashx
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
public class UploadHandler : IHttpHandler
{
private string uploadFolder = System.Configuration.ConfigurationManager.AppSettings["UploadFilePath"];
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
string orgName = "MyDomain";
string path = uploadFolder + orgName;
System.IO.Directory.CreateDirectory(path + "\\");
HttpPostedFile file = files[0];
if (file != null && file.ContentLength > 0)
{
string guid = System.Guid.NewGuid().ToString();
string savePath = path + "/" + guid + "_" + context.Request.Form["fileName"];
file.SaveAs(savePath);
string url = System.Configuration.ConfigurationManager.AppSettings["UploadFileUrl"] + orgName + "/" + guid + "_" + context.Request.Form["fileName"];
context.Response.Write(url);
}
}
else
{
context.Response.Write("");
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
3.flex应用程序
这部分google到核心程序来自
/*
Written by:
Dustin Andrew
dustin@flash-dev.com
http://www.flash-dev.com/
FileUpload
Panel component for uploading files.
(Icons from http://www.famfamfam.com/)
LAST UPDATED:
12/15/06
*/
使用flex builder 4.0新建项目UploadFiles
3.1 多文件上传组件
//FileUpload.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:com="*"
layout="vertical" width="581" minWidth="400" height="100%" minHeight="200"
title="上传文件" creationComplete="initCom()">
<mx:Metadata>
[Event(name="uploadComplete", type="flash.events.Event")]
[Event(name="uploadProgress", type="flash.events.ProgressEvent")]
[Event(name="uploadCancel", type="flash.events.Event")]
[Event(name="uploadIOError", type="flash.events.IOErrorEvent")]
[Event(name="uploadSecurityError", type="flash.events.SecurityErrorEvent")]
</mx:Metadata>
<mx:Script>
<![CDATA[
/*
Written by:
Dustin Andrew
dustin@flash-dev.com
http://www.flash-dev.com/
FileUpload
Panel component for uploading files.
(Icons from http://www.famfamfam.com/)
LAST UPDATED:
12/15/06
*/
import mx.controls.*;
import mx.managers.*;
import mx.events.*;
import flash.events.*;
import flash.net.*;
private var _strUploadUrl:String;
private var _refAddFiles:FileReferenceList;
private var _refUploadFile:FileReference;
private var _arrUploadFiles:Array;
private var _numCurrentUpload:Number = 0;
public function getURLs():String{
var urls:String = "";
for (var i:Number = 0; i < _arrUploadFiles.length; i++) {
urls = urls+"*"+_arrUploadFiles[i].url;
}
if(urls.length > 0)
urls = urls.substring(1);
return urls;
}
//private var _arrUploadFileURLs:Array;
// Set uploadUrl
public function set uploadUrl(strUploadUrl:String):void {
_strUploadUrl = strUploadUrl;
}
// Initalize
private function initCom():void {
_arrUploadFiles = new Array();
//_arrUploadFileURLs = new Array();
enableUI();
uploadCheck();
}
// Called to add file(s) for upload
private function addFiles():void {
_refAddFiles = new FileReferenceList();
_refAddFiles.addEventListener(Event.SELECT, onSelectFile);
_refAddFiles.browse();
}
// Called when a file is selected
private function onSelectFile(event:Event):void {
var arrFoundList:Array = new Array();
// Get list of files from fileList, make list of files already on upload list
for (var i:Number = 0; i < _arrUploadFiles.length; i++) {
for (var j:Number = 0; j < _refAddFiles.fileList.length; j++) {
if (_arrUploadFiles[i].name == _refAddFiles.fileList[j].name) {
arrFoundList.push(_refAddFiles.fileList[j].name);
_refAddFiles.fileList.splice(j, 1);
j--;
}
}
}
if (_refAddFiles.fileList.length >= 1) {
for (var k:Number = 0; k < _refAddFiles.fileList.length; k++) {
_arrUploadFiles.push({
name:_refAddFiles.fileList[k].name,
size:formatFileSize(_refAddFiles.fileList[k].size),
file:_refAddFiles.fileList[k],
url:""}
);
}
listFiles.dataProvider = _arrUploadFiles;
listFiles.selectedIndex = _arrUploadFiles.length - 1;
}
if (arrFoundList.length >= 1) {
Alert.show("The file(s): \n\n• " + arrFoundList.join("\n• ") + "\n\n...are already on the upload list. Please change the filename(s) or pick a different file.", "File(s) already on list");
}
updateProgBar();
scrollFiles();
uploadCheck();
}
// Called to format number to file size
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;
}
// Called to remove selected file(s) for upload
private function removeFiles():void {
var arrSelected:Array = listFiles.selectedIndices;
if (arrSelected.length >= 1) {
for (var i:Number = 0; i < arrSelected.length; i++) {
_arrUploadFiles[Number(arrSelected[i])] = null;
}
for (var j:Number = 0; j < _arrUploadFiles.length; j++) {
if (_arrUploadFiles[j] == null) {
_arrUploadFiles.splice(j, 1);
j--;
}
}
listFiles.dataProvider = _arrUploadFiles;
listFiles.selectedIndex = 0;
}
updateProgBar();
scrollFiles();
uploadCheck();
}
// Called to check if there is at least one file to upload
private function uploadCheck():void {
if (_arrUploadFiles.length == 0) {
btnUpload.enabled = false;
listFiles.verticalScrollPolicy = "off";
} else {
btnUpload.enabled = true;
listFiles.verticalScrollPolicy = "on";
}
}
// Disable UI control
private function disableUI():void {
btnAdd.enabled = false;
btnRemove.enabled = false;
btnUpload.enabled = false;
btnCancel.enabled = true;
listFiles.enabled = false;
listFiles.verticalScrollPolicy = "off";
}
// Enable UI control
private function enableUI():void {
btnAdd.enabled = true;
btnRemove.enabled = true;
btnUpload.enabled = true;
btnCancel.enabled = false;
listFiles.enabled = true;
listFiles.verticalScrollPolicy = "on";
}
// Scroll listFiles to selected row
private function scrollFiles():void {
listFiles.verticalScrollPosition = listFiles.selectedIndex;
listFiles.validateNow();
}
// Called to upload file based on current upload number
private function startUpload():void {
if (_arrUploadFiles.length > 0) {
disableUI();
listFiles.selectedIndex = _numCurrentUpload;
scrollFiles();
// Variables to send along with upload
var sendVars:URLVariables = new URLVariables();
sendVars.action = "upload";
var request:URLRequest = new URLRequest();
request.data = sendVars;
request.url = _strUploadUrl;
request.method = URLRequestMethod.POST;
_refUploadFile = new FileReference();
_refUploadFile = listFiles.selectedItem.file;
_refUploadFile.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
_refUploadFile.addEventListener(Event.COMPLETE, onUploadComplete);
_refUploadFile.addEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
_refUploadFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
_refUploadFile.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadCompleteData);
_refUploadFile.upload(request, "file", false);
}
}
// Cancel and clear eventlisteners on last upload
private function clearUpload():void {
_refUploadFile.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
_refUploadFile.removeEventListener(Event.COMPLETE, onUploadComplete);
_refUploadFile.removeEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
_refUploadFile.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
_refUploadFile.cancel();
_numCurrentUpload = 0;
updateProgBar();
enableUI();
}
// Called on upload cancel
private function onUploadCanceled():void {
clearUpload();
dispatchEvent(new Event("uploadCancel"));
}
// Get upload progress
private function onUploadProgress(event:ProgressEvent):void {
var numPerc:Number = Math.round((event.bytesLoaded / event.bytesTotal) * 100);
updateProgBar(numPerc);
var evt:ProgressEvent = new ProgressEvent("uploadProgress", false, false, event.bytesLoaded, event.bytesTotal);
dispatchEvent(evt);
}
// Update progBar
private function updateProgBar(numPerc:Number = 0):void {
var strLabel:String = (_numCurrentUpload + 1) + "/" + _arrUploadFiles.length;
strLabel = (_numCurrentUpload + 1 <= _arrUploadFiles.length && numPerc > 0 && numPerc < 100) ? numPerc + "% - " + strLabel : strLabel;
strLabel = (_numCurrentUpload + 1 == _arrUploadFiles.length && numPerc == 100) ? "Upload Complete - " + strLabel : strLabel;
strLabel = (_arrUploadFiles.length == 0) ? "" : strLabel;
progBar.label = strLabel;
progBar.setProgress(numPerc, 100);
progBar.validateNow();
}
// Called on upload complete
private function onUploadComplete(event:Event):void {
//listFiles.selectedIndex = _numCurrentUpload;
_numCurrentUpload++;
if (_numCurrentUpload < _arrUploadFiles.length) {
startUpload();
} else {
enableUI();
clearUpload();
dispatchEvent(new Event("uploadComplete"));
listFiles.dataProvider = _arrUploadFiles;
}
}
//
private function onUploadCompleteData(event:DataEvent):void{
_arrUploadFiles[_numCurrentUpload].url = event.data;
}
// Called on upload io error
private function onUploadIoError(event:IOErrorEvent):void {
clearUpload();
var evt:IOErrorEvent = new IOErrorEvent("uploadIoError", false, false, event.text);
dispatchEvent(evt);
}
// Called on upload security error
private function onUploadSecurityError(event:SecurityErrorEvent):void {
clearUpload();
var evt:SecurityErrorEvent = new SecurityErrorEvent("uploadSecurityError", false, false, event.text);
dispatchEvent(evt);
}
// Change view state
private function changeView():void {
currentState = (currentState == "mini") ? "" : "mini";
}
]]>
</mx:Script>
<mx:states>
<mx:State name="mini">
<mx:SetProperty name="height" value="60"/>
<mx:SetProperty name="minHeight" value="60"/>
<mx:SetStyle target="{btnView}" name="icon" value="@Embed('assets/application_put.png')"/>
</mx:State>
</mx:states>
<mx:transitions>
<mx:Transition fromState="*" toState="*">
<mx:Resize target="{this}" duration="1000"/>
</mx:Transition>
</mx:transitions>
<mx:Canvas width="100%" height="100%">
<mx:DataGrid id="listFiles" left="0" top="0" bottom="0" right="0"
allowMultipleSelection="true" verticalScrollPolicy="on"
draggableColumns="false" resizableColumns="false" sortableColumns="false" width="582">
<mx:columns>
<mx:DataGridColumn headerText="文件名" dataField="name" wordWrap="true"/>
<mx:DataGridColumn headerText="大小" dataField="size" width="75" textAlign="right"/>
<mx:DataGridColumn dataField="url" headerText="URL"/>
</mx:columns>
</mx:DataGrid>
</mx:Canvas>
<mx:ControlBar horizontalAlign="center" verticalAlign="middle">
<mx:Button id="btnAdd" toolTip="增加文件" click="addFiles()" icon="@Embed('assets/add.png')" width="26"/>
<mx:Button id="btnRemove" toolTip="移除文件" click="removeFiles()" icon="@Embed('assets/delete.png')" width="26"/>
<mx:ProgressBar id="progBar" mode="manual" label="" labelPlacement="center" width="100%"/>
<mx:Button id="btnCancel" toolTip="取消上传mailto:%22%20icon=%22@Embed('assets/cancel2.png')" width="26" click="onUploadCanceled()"/>
<mx:Button label="上传" toolTip="上传文件" id="btnUpload" click="startUpload()" icon="@Embed('assets/bullet_go.png')"/>
<mx:Button id="btnView" toolTip="显示/隐藏文件mailto:%22%20icon=%22@Embed('assets/application_get.png')" width="26" click="changeView()"/>
</mx:ControlBar>
</mx:Panel>
3.2.文件上传程序
//UploadFiles.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:com="com.flashdev.file.*" layout="absolute"
creationComplete="initApp()" viewSourceURL="srcview/index.html" width="653" height="429">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private const _strDomain:String = new String("http://www.mydomain.com/");
private const _strUploadScript:String = new String(_strDomain + "uploadhandler.ashx");
// Initalize
private function initApp():void {
Security.allowDomain(_strDomain);
//ExternalInterface.addCallback("getURLs",getURLs);
}
public function getURLs():String{
var urls:String = filesUpload.getURLs();
return urls;
}
private function closeWindow():void{
ExternalInterface.call("closeWindow");
}
private function okWindow():void{
ExternalInterface.call("okWindow",getURLs());
}
]]>
</mx:Script>
<mx:Canvas width="502" height="336" horizontalCenter="0" verticalCenter="0" y="42" x="78">
<com:FileUpload id="filesUpload"
width="488" height="324"
uploadUrl="{_strUploadScript}"
uploadComplete="Alert.show('文件上传完毕,确定返回。', '上传成功')"
uploadIOError="Alert.show('正在上传的文件发生错误。', '错误')"
uploadSecurityError="Alert.show('安全错误。', '错误')" x="7" y="4"/>
</mx:Canvas>
<mx:Button x="507" y="398" label="关闭" click="closeWindow()"/>
<mx:Button x="426" y="398" label="确定" click="okWindow()"/>
</mx:Application>
3.3.修改index.template.html文件
也是增加一段js
<script type="text/javascript">
function okWindow(urls) {
window.returnValue = urls;
window.close();
}
function closeWindow(){
window.close();
}
</script>
4.把编译好的flash上传到站点/uploadfiles下面
5.使用
<HTML>
<HEAD>
<script language="javascript" >
function ShowFlexUploadFile(fileUrlTextBox){
if(fileUrlTextBox != ""){
var currentFileUrlTextBox = document.all[fileUrlTextBox];
var result=window.showModalDialog("/uploadfiles/UploadFiles.html","","dialogWidth:400px;dialogHeight:300px;center=yes;");
if(result == "") return;
if(typeof(result)=="undefined") return;
currentFileUrlTextBox.value = result;
}
}
</script>
</HEAD>
<BODY>
<input type='text' ID="txtFileUrl" style="width:220px" /> <a href="javascript:void(0)" title="Upload File" onclick="javascript:ShowFlexUploadFile('txtFileUrl');" >Upload</a>
</BODY>
</HTML>