ASP.NET实现多文件上传的方法

首先声明一点,本方法上传类大部分参考自laifangsong的文章“单/多文件上传”,我不过是作了小小改动和增加了调用的ASCX控件,原文地址是:http://jiny-z.cnblogs.com/archive/2006/04/17/377184.html

来看看前台的upload.ascx文件:

 

<%@ Control Inherits="Upload.myUploadFiles"%>
<script language="javascript">
  
function addFileControl()
  
{
      
var str='<input type="file" id="InputFile" name="InputFile" size="64"><br />'
      document.getElementById('FileCollection').insertAdjacentHTML(
"beforeEnd",str)
  }

</script>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
    
<tr>
        
<td id="FileCollection">
            
<input type="file" id="InputFile" name="InputFile" size="64"><br />
        
</td>
    
</tr>
    
<tr>
        
<td>
        
<input type="submit" value="Submit to Post" /> <input type="button" value="增加(File)" onClick="addFileControl()">
        
</td>
    
</tr>
    
<tr>
        
<td>
            
<asp:Literal id="ltrInfo" runat="server" /><br />
        
</td>
    
</tr>
</table>


ascx文件的后台代码是:

 

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using QS_Web.Upload;

namespace Upload
{
    
public class myUploadFiles : UserControl
    
{
        
protected Literal ltrInfo;
        
private void Page_Load(object sender, EventArgs e)
        
{
            UploadFiles myUploadFiles 
= new UploadFiles();
            myUploadFiles.BoolUseAbsolutePath 
= false;
            myUploadFiles.StrUploadPath 
= @"up";
            myUploadFiles.BoolUseRandFileName 
= false;
            myUploadFiles.BoolCreateDateDir 
= false;
            myUploadFiles.Upload();

            ltrInfo.Text 
= myUploadFiles.GetInfo();
        }

    }

}

    


可以看到ascx文件主要作用就是调用UploadFiles类来实现多文件上传,我们再来看看uploadfiles类:

 

public class UploadFiles// 单/多文件上传
        {
        
            
//上传文件默认目录,例如: UploadFiles,该值在web.config中配置
            private string strInitDirectory = Read.GetConfigSetting("UploadDir");

            
//是否启用绝对路径,该路径一般会存在数据库中。若设为绝对路径,调用不用考虑相对路径问题
            private bool boolUseAbsolutePath = false;

            
//上传路径,例如:上传路径是 Pic,那么所有的图片都会存在 UploadFiles/Pic目录下,为空时全部存在 UploadFiles目录下
            private string strUploadPath = String.Empty;

            
//是否启用随机文件名,随机文件名的格式是:yyyyMMddhhmmss + 3位数的随机数
            private bool boolUseRandFileName = true;

            
//是否自动创建日期目录,若启用,会在上传文件目录下生成 2006/4/17 这3个目录
            private bool boolCreateDateDir = true;

            
//返回提示信息
            private string strInfo = String.Empty;

            
public bool BoolUseAbsolutePath
            
{
                
get
                
{
                    
return boolUseAbsolutePath;
                }

                
set
                
{
                    boolUseAbsolutePath 
= value;
                }

            }

            
public string StrUploadPath
            
{
                
get
                
{
                    
return strUploadPath;
                }

                
set
                
{
                    
if(boolUseAbsolutePath) //如果启用绝对路径
                    {
                        strUploadPath 
= value.ToString().Trim();
                        
if(!strUploadPath.EndsWith(@"\"))
                        
{
                            strUploadPath 
+= @"\";
                        }

                    }

                    
else
                    
{
                        strUploadPath 
= GetApplicationPath(); //取得虚拟根路径
                        if(this.strInitDirectory == "null")//定位到默认目录
                        {
                            
string str = "uploadfiles";
                            strUploadPath 
+= str + "/";
                        }

                        
else
                        
{
                            strUploadPath 
+= this.strInitDirectory + "/";
                        }

                        
string strValueExtended = value.ToString().Trim();
                        
if(strValueExtended != ""//如果输入的上传目录不为空,则将路径定位到该目录
                        {
                            strUploadPath 
+= value;
                            
if(!strValueExtended.EndsWith("/"))
                            
{
                                strUploadPath 
+= "/";
                            }

                        }

                    }

                }

            }


            
public bool BoolUseRandFileName //是否启用随机文件名
            {
                
get
                
{
                    
return boolUseRandFileName;
                }

                
set
                
{
                    boolUseRandFileName 
= value;
                }

            }

            
public bool BoolCreateDateDir //是否自动创建日期目录
            {
                
get
                
{
                    
return boolCreateDateDir;
                }

                
set
                
{
                    boolCreateDateDir 
= value;
                }

            }

            
public void Upload()
            
{
                HttpFileCollection hpc 
= HttpContext.Current.Request.Files; //获取客户端上载的文件集合            
                if(hpc != null)
                
{
                    
for(int i=0; i<hpc.Count; i++)
                    
{
                        HttpPostedFile file 
= hpc[i];
                        
int intFileContentLength = file.ContentLength;//判断文件大小,返回的是字节
                        if(intFileContentLength < 1//空文件处理
                        {
                            strInfo 
+= "<br />文件为空文件,请查正再上传!";
                            
return;
                        }

                        
int intAllowMaxSize;
                        
try
                        
{
                            intAllowMaxSize 
= Convert.ToInt32(Read.GetConfigSetting("UploadMaxSize"));
                        }

                        
catch
                        
{
                            intAllowMaxSize 
= 2000;
                        }

                        
if(intFileContentLength > intAllowMaxSize * 1024)
                        
{
                            strInfo 
= "<br />最大上传的文件只允许<font color=red> " + intAllowMaxSize.ToString() + " </font>K";
                            
return;
                        }

                        
string strFileName = Path.GetFileName(file.FileName);
                        
string strFileContentType = Path.GetExtension(strFileName).Remove(01); //返回指定的路径字符串的扩展名
                        string strAllowTypes = Read.GetConfigSetting("UploadTypes");
                        
if(strAllowTypes != "null")
                        
{
                            
//判断类型是否在允许类型列表中,这样写,允许列表必须用"|"分隔允许类型
                            if(("|"+strAllowTypes.ToLower()+"|").IndexOf("|"+strFileContentType.ToLower()+"|"== -1
                            
{
                                strInfo 
+= "<br />只允许上传的文件格式有:<font color=red> " + strAllowTypes + " </font>";
                                
return;
                            }

                        }

                        
//随机文件名
                        if(boolUseRandFileName)
                        
{
                            strFileName 
= DateTime.Now.ToString("yyyyMMddhhmmss"+ (new Random()).Next(1001000).ToString() + "." + strFileContentType;
                        }

                        
string strFilePath,strAddPath;
                        
if(boolUseAbsolutePath)
                        
{
                            
if(!Directory.Exists(strUploadPath)) //确定目录是否存在,如果否,则创建目录
                            {
                                Directory.CreateDirectory(strUploadPath);
                            }

                            strAddPath 
= strUploadPath;
                        }

                        
else
                        
{
                            
if(strUploadPath == String.Empty)
                            
{
                                
if(this.strInitDirectory == "null")//定位到默认目录
                                {
                                    
string str = "uploadfiles";
                                    strUploadPath 
+= str + "/";
                                }

                                
else
                                
{
                                    strUploadPath 
+= this.strInitDirectory + "/";
                                }

                            }

                            strAddPath 
= HttpContext.Current.Server.MapPath(strUploadPath); //返回与指定虚拟路径相对应的物理文件路径
                            if(!Directory.Exists(strAddPath)) //确定目录是否存在,如果否,则创建目录
                            {
                                Directory.CreateDirectory(strAddPath);
                            }

                        }

                        
if(boolCreateDateDir)//如果创建日期目录,则创建
                        {
                            strAddPath 
+= DateTime.Today.Year.ToString() + @"\";
                            
if(!Directory.Exists(strAddPath))
                            
{
                                Directory.CreateDirectory(strAddPath);
                            }

                            strAddPath 
+= DateTime.Today.Month.ToString().PadLeft(2'0'+ @"\";
                            
if(!Directory.Exists(strAddPath))
                            
{
                                Directory.CreateDirectory(strAddPath);
                            }

                            strAddPath 
+= DateTime.Today.Day.ToString().PadLeft(2'0'+ @"\";
                            
if(!Directory.Exists(strAddPath))
                            
{
                                Directory.CreateDirectory(strAddPath);
                            }

                        }

                        strFilePath 
= strAddPath + strFileName;
                        file.SaveAs((strFilePath));
                        
                        
string strLocalPath = HttpContext.Current.Server.MapPath(null);
                        
string strUrl = strFilePath.Replace(strLocalPath,"");

                        strInfo 
+= "<br />文件<font color=red> "+ strFileName + " </font>上传成功!";
                        
//strInfo += "<br />地址:<font color=red> " + strFilePath +" </font>";
                        strInfo += "<br />文件地址:<font color=red> " + strUrl +" </font>";
                    }

                }

            }


            
public string GetInfo()
            
{
                
return strInfo;
            }


            
private string GetApplicationPath() //取得虚拟根路径
            {
                
string strAppPath = HttpContext.Current.Request.ApplicationPath;  //获取应用程序的虚拟应用程序根路径
                if(!strAppPath.EndsWith("/"))
                
{
                    strAppPath 
+= "/"
                }

                
return strAppPath;
            }

    
        }


对原来代码的修改主要修改的是文件存放位置的定位上,原来的代码在测试的时候出现一些细微的错误,我改正了,并按照我自己的意愿作了一些修改,现在使用该类主要要注意的是:

代码会在Web.config文件中搜索名为"UploadDir"的设置,当上传设定为非绝对路径时候,该设置设定上传路径的上传目录,所有文件及程序中设置的目录路径均在该设置设定的文件夹下,如果该设置为空,则默认目录是根目录下的uploadfiles目录;
代码会在Web.config文件中搜索名为"UploadMaxSize"的设置,该设置设定上传文件的大小,单位为K如果该设置为空,则默认是2000K;
代码会在Web.config文件中搜索名为"UploadTypes"的设置,该设置设定上传文件的类型,格式是"jpg|gif|bmp",如果该设置为空,则默认可以上传所有类型文件。一定要设置上传文件类型,否则有极大隐患!

感谢laifangsong给我们带来了如此精彩的代码!

最后批评或建议请留言或直接Email给我:kenblove#gmail.com(记得将#换@哦)

posted @ 2006-07-30 13:01  KenBlove  阅读(717)  评论(0)    收藏  举报