最近在网上下了个flash的代码实现批量上传功能的
然后所有的问题我都解决了现在剩下的问题就是我获取上传文件名的时候,有的时候能全部正确获取,
有的时候却只能获取到其中一部分文件的名字,还有一部分文件的名字不能正常获取,
小弟在这里贴出flash的action代码,还有响应flash是想上传的asp.net代码,求各位大哥们兄弟们帮帮忙
告诉我怎么正确的获取这个flash传给后台的文件名。
flash的astion代码:
// Based off the tutorial found at http://shu.ca/imm/flash/tutorial/fileReference.html
// changed to use FileReferenceList for multiple file selection.//import the FileReference Object
import flash.net.FileReference;
import flash.net.FileReferenceList;//initial settings - since no upload file type selet yet user cannot upload a file
uploadButn.enabled = false;
//create a new FileReference object
var fileRefList:FileReferenceList = new FileReferenceList();// variables to keep track of how many bytes have been uploaded so far //and you many more to go
var totalBytes:Number = 0;
var uploadedBytes:Number = 0;
var uploadedBytes2:Array;// variables to keep track of completed files
var filesCompleted:Number = 0;
var totalFiles:Number = 0;
//create a listener object for FileReference events
var fileRefListener:Object = new Object();//Use to limit the type of files in the browse dialog box
//fileDescription = "Images and Zips";
//fileExtension = "*.jpg; *.jpeg; *.gif; *.png; *.zip";_root.progressBar.visible = false;//a small function to redraw (reset) the progress bar
function reDrawPB (pb, xCor, yCor) {
_root.destroyObject(pb);
_root.createObject("ProgressBar",pb,0);
    _root.progressBar.move(xCor,yCor);
_root.progressBar.label = "UPLOADING %3%% ";
}//===================== FILEREFERENCE EVENT HANDLER =====================////When user selects a file from the file-browsing dialog box, 
//the onSelect() method is called, and passed a reference to the FileReference objectfileRefListener.onSelect = function (fileRefList:FileReferenceList):Void {
// allow user to upload
uploadButn.enabled = true;
reDrawPB("progressBar", 272.0, 43.0);
status_txt.text = "Files selected to upload: \n";
status_txt.vPosition = status_txt.maxVPosition;
var list:Array = fileRefList.fileList;
    var fileRef:FileReference;
// set totalbytes to 0 and then add the file sizes up
totalBytes = 0;
// loop through FileReferenceList and print out all the files selected
    for(var i:Number = 0; i < list.length; i++) {
        fileRef = list[i];
totalBytes += fileRef.size;
status_txt.text += fileRef.name + '\n';
status_txt.vPosition = status_txt.maxVPosition;
    }
// show the total file size
status_txt.text += list.length + " file(s) selected at ";
status_txt.text += GetSizeType(totalBytes);
status_txt.vPosition = status_txt.maxVPosition;
}//When user dismiss the file-browsing dialog box, 
//the onCancel() method is called, and passed a reference to the //FileReference object
fileRefListener.onCancel = function (fileRef:FileReference):Void {
uploadButn.enabled = false;
status_txt.text ="No files selected. \n";
status_txt.vPosition = status_txt.maxVPosition;
}//When the file upload/download process started, 
//the onOpen() method is called, and passed a reference to the //FileReference object
fileRefListener.onOpen = function (fileRef:FileReference):Void {
status_txt.text +="Uploading " + fileRef.name + " please wait...\n";
status_txt.vPosition = status_txt.maxVPosition;
}//The onProgress() method is called periodically during the file upload //operation
fileRefListener.onProgress = function (fileRef:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {
//setting the status bar function
progressBar.mode = "manual";
// Allows us to keep track of the total amount uploaded and set the progress bar
var temp:Number = bytesLoaded - uploadedBytes2[fileRef.name]
uploadedBytes2[fileRef.name] = bytesLoaded;
uploadedBytes += temp;
progressBar.setProgress(uploadedBytes, totalBytes);
txtUploaded.text = GetSizeType(uploadedBytes);
txtTotal.text = GetSizeType(totalBytes);}//When the file upload/download operation is successfully complete, 
//the onComplete() method is called, and passed a reference to the FileReference object
fileRefListener.onComplete = function (fileRef:FileReference):Void {
status_txt.text += fileRef.name + " uploaded.\n";
status_txt.vPosition = status_txt.maxVPosition;
//upload is now complete, increment fileCompleted and write out to display
filesCompleted++;
status_txt.text +=  filesCompleted + " of " + totalFiles + " files completed.\n";
status_txt.vPosition = status_txt.maxVPosition;
// Once all files are uploaded, call the FinishUpload function to //finish things up
if(filesCompleted == totalFiles)
FinishedUpload();
}fileRefListener.onHTTPError = function(fileRef:FileReference):Void {
// show error to user
status_txt.text += "There was an error uploading " + fileRef.name + "\n";
status_txt.vPosition = status_txt.maxVPosition;
}fileRefListener.onIOError = function(fileRef:FileReference):Void {
    //trace("onIOError: " + file.name);
// show error to user
status_txt.text += "There was an IO error uploading " + fileRef.name + "\n";
status_txt.vPosition = status_txt.maxVPosition;
}fileRefListener.onSecurityError = function(fileRef:FileReference, errorString:String):Void {
    //trace("onSecurityError: " + file.name + " errorString: " + errorString);
// show error to user
status_txt.text += "There was a security error accessing " + fileRef.name + " errorString: " + errorString +  "\n";
status_txt.vPosition = status_txt.maxVPosition;
}//****************************************************************************************////attach Listener to the FileReference Object
fileRefList.addListener(fileRefListener);//button event for the browse button
browseButn.clickHandler = function () {
//The browse function is the key, coz it displays a file-browsing dialog box
//in which the user can select a local file to upload
// if you want to limit the types of files the user can select to //upload use the following
// these are set earlier in the code
//fileRefList.browse([{description: fileDescription, extension: fileExtension}]);
// otherwise, just call the browse function.
fileRefList.browse();
}//Button event for the upload button
uploadButn.clickHandler = function () {
var list:Array = fileRefList.fileList;
var fileRef:FileReference;
// the upload button also acts as the cancel upload button.
if(uploadButn.label == "UPLOAD")
{
browseButn.enabled = false;
uploadButn.label = "CANCEL";
status_txt.text = "Starting Upload:" + '\n';
status_txt.vPosition = status_txt.maxVPosition;
totalFiles = list.length;
// these help keep track of how much has been uploaded, used in the onProgress even.
filesCompleted = 0;
uploadedBytes = 0;
uploadedBytes2 = [];
// I'm not the best at action script. I tried to set visible to false on the txtOf
// and then show it when ready, but it wasn't working, so I'm just setting the text instead.
txtOf.text = "of";
// loop through the list of FileReferences and add the event handler to them, and then 
// call the upload function
for(var i:Number = 0; i < list.length; i++) {
fileRef = list[i];
status_txt.text +="Attempting to upload " + fileRef.name + '\n';
status_txt.vPosition = status_txt.maxVPosition;
fileRef.addListener(fileRefListener)
// This keeps track of the upload to show how much has been uploaded for each file,
// it is used in the onProgress event.
uploadedBytes2[fileRef.name] = 0;
//upload the file to the httphandler on the server
// uploadPage is set in the asp.net page, it is a LoadVars variable.
// if it isn't set, it won't upload.  This allows you to vary the page you upload to,
// as well as pass in any query string arguments needed for the upload.
// you can also tack on a custom file name here if you wanted.
// depending on the uploadPage value just do something like uploadPage + "?Filename=" + customFilename
// then you handle the file name on the server side.
if(uploadPage != undefined)
fileRef.upload(uploadPage);
}
}
else
{
status_txt.text += "Upload Canceled." + '\n';
status_txt.vPosition = status_txt.maxVPosition;
for(var i:Number = 0; i < list.length; i++) {
fileRef = list[i];
fileRef.cancel();
}
uploadButn.label = "UPLOAD";
browseButn.enabled = true;
}
}// finish the upload
function FinishedUpload()
{
uploadButn.enabled = false;
uploadButn.label = "UPLOAD";
browseButn.enabled = true;
// this allows you to pass in a javascript function to call after the download
// Say you have a gridView displaying the files you've uploaded, you can use this
// to refresh the gridView by doing a postback.  Only called if it is set. Also a
// LoadVars variable.
if(completeFunction != undefined)
{
getURL('javascript:' + completeFunction);
}
}// Converts bytes into more redable values. Called from onProgress.
function GetSizeType(size:Number)
{
if(size < 1024)
return int(size*100)/100 + " bytes";
if(size < 1048576)
return int((size / 1024)*100)/100 + "KB";
if(size < 1073741824)
   return int((size / 1048576)*100)/100 + "MB";
 return int((size / 1073741824)*100)/100 + "GB";
}

解决方案 »

  1.   

    后台响应flash的代码:
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.IO;
    using System.Collections;/// <summary>
    /// Upload handler for uploading files.
    /// </summary>
    public class Upload : IHttpHandler
    {
        ArrayList al = new ArrayList();
        public Upload()
        {
            al = new ArrayList();
        }    #region IHttpHandler Members    public bool IsReusable
        {
            get { return true; }
        }
        public void ProcessRequest(HttpContext context)
        {
            // Example of using a passed in value in the query string to set a categoryId
            // Now you can do anything you need to witht the file.
            //int categoryId = 0;
            //if (context.Request.QueryString["CategoryID"] != null)
            //{
            //    try
            //    {
            //        categoryId = Convert.ToInt32(context.Request.QueryString["CategoryID"]);
            //    }
            //    catch (Exception err)
            //    {
            //        categoryId = 0;
            //    }
            //}
            //if (categoryId > 0)
            //{
            //}
            if (context.Request.Files.Count > 0)
            {
                // get the applications path
               string tempFile = context.Request.PhysicalApplicationPath;
                // loop through all the uploaded files
                // get the current file
               HttpFileCollection file = context.Request.Files;
               HttpPostedFile uploadFile1 = file[0];
                    string name = uploadFile1.FileName;
                    // if there was a file uploded
                    al.Add(name);
                    if (al != null)
                    {
                        context.Application["test"] = al;
                    }
                            for (int k = 0; k < context.Request.Files.Count; k++)
                            {
                                HttpPostedFile uploadFile = context.Request.Files[0];
                                if (uploadFile.ContentLength > 0)
                                {
                                    // save the file to the upload directory                                //use this if testing from a classic style upload, ie.                                 // <form action="Upload.axd" method="post" enctype="multipart/form-data">
                                    //    <input type="file" name="fileUpload" />
                                    //    <input type="submit" value="Upload" />
                                    //</form>                                // this is because flash sends just the filename, where the above 
                                    //will send the file path, ie. c:\My Pictures\test1.jpg                              
                                    // use this if using flash to upload
                                   string tt= DateTime.Now.ToString("yyyy-MM-dd");
                                   string realname = tt +"-"+ uploadFile.FileName.Replace(" ","");
                                    uploadFile.SaveAs(string.Format("{0}{1}{2}", tempFile, "Upload\\", realname));
                                    // HttpPostedFile has an InputStream also.  You can pass this to 
                                    // a function, or business logic. You can save it a database:                                //byte[] fileData = new byte[uploadFile.ContentLength];
                                    //uploadFile.InputStream.Write(fileData, 0, fileData.Length);
                                    // save byte array into database.                                // something I do is extract files from a zip file by passing
                                    // the inputStream to a function that uses SharpZipLib found here:
                                    // http://www.icsharpcode.net/OpenSource/SharpZipLib/
                                    // and then save the files to disk.
                                }
                            }
            }
            // Used as a fix for a bug in mac flash player that makes the 
            // onComplete event not fire
            HttpContext.Current.Response.Write(" ");
        }
        #endregion
    }
      

  2.   

    前台代码也贴出来吧
    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Flash Upload</title>
        <script language="javascript" src="js/jquery-1.4.2.js"></script>
        <script language="javascript" src="js/defalut.js"></script>
        <script language="javascript" src="js/menu/popcalendar.js"></script>
    </head>
    <body>
        <form id="form1" runat="server" enctype="multipart/form-data" method="POST">
        <div>
            <%--
            
            Adding the flash uploader to the page.  <param name="wmode" value="transparent"> makes
            the movie transparent so any page styling can shine through.
            FlashVars is set to pass in the upload page and a javascript function if desired.
            The javascript function fires when the upload is completed.  This allows us to 
            call a codebehind function to refresh a gridView or anything else.
            A link button is used to perform this function.  The javascript is added in the pageLoad 
            in the code behin.
            To edit the flash file, Adobe/Macromedia has a 30-day trial of Macromedia Flash
            for download.  After that, you're on your own.
            --%>
            <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
             codebase="www.mds.com.cn"
             width="550" height="100" id="fileUpload" align="middle">
                <param name="allowScriptAccess" value="sameDomain" />
                <param name="movie" value="fileUpload.swf" />
                <param name="quality" value="high" />
                <param name="wmode" value="transparent">
                <PARAM NAME=FlashVars VALUE='uploadPage=Upload.axd<%=GetFlashVars()%>&completeFunction=UploadComplete()'>
                <embed src="fileUpload.swf"
                 FlashVars='uploadPage=Upload.axd<%=GetFlashVars()%>&completeFunction=UploadComplete()'
                 quality="high" wmode="transparent" width="550" height="100" 
                 name="fileUpload" align="middle" allowScriptAccess="sameDomain" 
                 type="application/x-shockwave-flash" 
                 pluginspage="" />
            </object>
            <%--This link button is here so we can call the LinkButton1_Click even from javascript.
                Make the text empty so the link doesn't show up on the page.--%>
            <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>
           <asp:TextBox ID="take" runat="server" style="display:none"></asp:TextBox> 
        </div>
                   </div>
        </form>
        </body>
    </html>
      

  3.   

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.OleDb;public partial class _Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                // allows the javascript function to do a postback and call the onClick method
                // associated with the linkButton LinkButton1.
                string jscript = "function UploadComplete(){";
                jscript += string.Format("__doPostBack('{0}','');", LinkButton1.ClientID.Replace("_", "$"));
                jscript += "};";
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "FileCompleteUpload", jscript, true);
                ArrayList kk = Context.Application["test"] as ArrayList;
                string kd = "";
                if (kk != null)
                {
                    foreach (string dr in kk)
                    {
                        if (kd != null && kd != "")
                        {
                            kd = kd + "[xc]" + dr;
                        }
                        else
                        {
                            kd = dr;
                        }
                    }
                    take.Text = kd;
                    kk.Clear();
                }
        }
        protected string GetFlashVars()
        {
            // Adds query string info to the upload page
            // you can also do something like:
            // return "?" + Server.UrlEncode("CategoryID="+CategoryID);
            // we UrlEncode it because of how LoadVars works with flash,
            // we want a string to show up like this 'CategoryID=3&UserID=4' in
            // the uploadPage variable in flash.  If we passed this string withou
            // UrlEncode then flash would take UserID as a seperate LoadVar variable
            // instead of passing it into the uploadPage variable.
            // then in the httpHandler we get the CategoryID and UserID values from 
            // the query string. See Upload.cs in App_Code
            return "?" + Server.UrlEncode("CategoryID="+5);
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            int i =HttpContext.Current.Request.Files.Count;
            if (i > 0)
            {
                string oo = HttpContext.Current.Request.Files[0].ToString();
            }
            // Do something that needs to be done such as refresh a gridView
            // say you had a gridView control called gvMyGrid displaying all 
            // the files uploaded. Refresh the data by doing a databind here.
            // gvMyGrid.DataBind();    }}
      

  4.   

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.OleDb;public partial class _Default : System.Web.UI.Page  
    {
      protected void Page_Load(object sender, EventArgs e)
      {
      // allows the javascript function to do a postback and call the onClick method
      // associated with the linkButton LinkButton1.
      string jscript = "function UploadComplete(){";
      jscript += string.Format("__doPostBack('{0}','');", LinkButton1.ClientID.Replace("_", "$"));
      jscript += "};";
      Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "FileCompleteUpload", jscript, true);
      ArrayList kk = Context.Application["test"] as ArrayList;
      string kd = "";
      if (kk != null)
      {
      foreach (string dr in kk)
      {
      if (kd != null && kd != "")
      {
      kd = kd + "[xc]" + dr;
      }
      else
      {
      kd = dr;
      }
      }
      take.Text = kd;
      kk.Clear();
      }
      }
      protected string GetFlashVars()
      {
      // Adds query string info to the upload page
      // you can also do something like:
      // return "?" + Server.UrlEncode("CategoryID="+CategoryID);
      // we UrlEncode it because of how LoadVars works with flash,
      // we want a string to show up like this 'CategoryID=3&UserID=4' in
      // the uploadPage variable in flash. If we passed this string withou
      // UrlEncode then flash would take UserID as a seperate LoadVar variable
      // instead of passing it into the uploadPage variable.
      // then in the httpHandler we get the CategoryID and UserID values from  
      // the query string. See Upload.cs in App_Code
      return "?" + Server.UrlEncode("CategoryID="+5);
      }
      protected void LinkButton1_Click(object sender, EventArgs e)
      {
      int i =HttpContext.Current.Request.Files.Count;
      if (i > 0)
      {
      string oo = HttpContext.Current.Request.Files[0].ToString();
      }
      // Do something that needs to be done such as refresh a gridView
      // say you had a gridView control called gvMyGrid displaying all  
      // the files uploaded. Refresh the data by doing a databind here.
      // gvMyGrid.DataBind();  }}
      

  5.   

    http://www.uploadify.com/demos/
    这是个jquery批量上传插件..你看看
      

  6.   

    如果不熟悉FLEX还是不要用了.
      

  7.   

    现弄一个版本对付上去,在客户发现问题之前主抓flex。你现在在这里贴一堆又臭又长的代码(不知道你哪儿弄来的)基本上没人会耐心看完并给你做出合理解释的。还有,下次贴代码之前,先把注释都删掉
      

  8.   

    多谢大哥提醒,
    现在我不是要提交给客户,是要提交给我们老大~~~~,我要崩溃了29号回家的火车票啊明天还没弄出来就回不了家了
    不管你能不能听懂我 直接给你说我的问题了,
    现在是我能从flash中获取到上传的文件名,但是我在后台需要将这个文件名再获取一次,就这里出问题,我再获取这个文件名的时候就有问题了,要么就少获取几个要么就获取了上次提交的文件名,有的时候还是能正确获取的。
    我的问题就这里,不知道大哥们碰到过没有