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

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

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

 

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

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


ascx文件的后台代码是:

 

None.gif using  System;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  QS_Web.Upload;
None.gif
None.gif
namespace  Upload
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public class myUploadFiles : UserControl
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
protected Literal ltrInfo;
InBlock.gif        
private void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            UploadFiles myUploadFiles 
= new UploadFiles();
InBlock.gif            myUploadFiles.BoolUseAbsolutePath 
= false;
InBlock.gif            myUploadFiles.StrUploadPath 
= @"up";
InBlock.gif            myUploadFiles.BoolUseRandFileName 
= false;
InBlock.gif            myUploadFiles.BoolCreateDateDir 
= false;
InBlock.gif            myUploadFiles.Upload();
InBlock.gif
InBlock.gif            ltrInfo.Text 
= myUploadFiles.GetInfo();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif    


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

 

None.gif public   class  UploadFiles //  单/多文件上传
ExpandedBlockStart.gifContractedBlock.gif
         dot.gif {
InBlock.gif        
InBlock.gif            
//上传文件默认目录,例如: UploadFiles,该值在web.config中配置
InBlock.gif
            private string strInitDirectory = Read.GetConfigSetting("UploadDir");
InBlock.gif
InBlock.gif            
//是否启用绝对路径,该路径一般会存在数据库中。若设为绝对路径,调用不用考虑相对路径问题
InBlock.gif
            private bool boolUseAbsolutePath = false;
InBlock.gif
InBlock.gif            
//上传路径,例如:上传路径是 Pic,那么所有的图片都会存在 UploadFiles/Pic目录下,为空时全部存在 UploadFiles目录下
InBlock.gif
            private string strUploadPath = String.Empty;
InBlock.gif
InBlock.gif            
//是否启用随机文件名,随机文件名的格式是:yyyyMMddhhmmss + 3位数的随机数
InBlock.gif
            private bool boolUseRandFileName = true;
InBlock.gif
InBlock.gif            
//是否自动创建日期目录,若启用,会在上传文件目录下生成 2006/4/17 这3个目录
InBlock.gif
            private bool boolCreateDateDir = true;
InBlock.gif
InBlock.gif            
//返回提示信息
InBlock.gif
            private string strInfo = String.Empty;
InBlock.gif
InBlock.gif            
public bool BoolUseAbsolutePath
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
get
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return boolUseAbsolutePath;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
set
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    boolUseAbsolutePath 
= value;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
public string StrUploadPath
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
get
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return strUploadPath;
ExpandedSubBlockEnd.gif                }

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

ExpandedSubBlockEnd.gif                    }

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

InBlock.gif                        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            strUploadPath 
+= this.strInitDirectory + "/";
ExpandedSubBlockEnd.gif                        }

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

ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public bool BoolUseRandFileName //是否启用随机文件名
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                
get
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return boolUseRandFileName;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
set
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    boolUseRandFileName 
= value;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
public bool BoolCreateDateDir //是否自动创建日期目录
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                
get
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return boolCreateDateDir;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
set
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    boolCreateDateDir 
= value;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

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

InBlock.gif                        
int intAllowMaxSize;
InBlock.gif                        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            intAllowMaxSize 
= Convert.ToInt32(Read.GetConfigSetting("UploadMaxSize"));
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            intAllowMaxSize 
= 2000;
ExpandedSubBlockEnd.gif                        }

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

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

ExpandedSubBlockEnd.gif                        }

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

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

InBlock.gif                            strAddPath 
= strUploadPath;
ExpandedSubBlockEnd.gif                        }

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

InBlock.gif                                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    strUploadPath 
+= this.strInitDirectory + "/";
ExpandedSubBlockEnd.gif                                }

ExpandedSubBlockEnd.gif                            }

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

ExpandedSubBlockEnd.gif                        }

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

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

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

ExpandedSubBlockEnd.gif                        }

InBlock.gif                        strFilePath 
= strAddPath + strFileName;
InBlock.gif                        file.SaveAs((strFilePath));
InBlock.gif                        
InBlock.gif                        
string strLocalPath = HttpContext.Current.Server.MapPath(null);
InBlock.gif                        
string strUrl = strFilePath.Replace(strLocalPath,"");
InBlock.gif
InBlock.gif                        strInfo 
+= "<br />文件<font color=red> "+ strFileName + " </font>上传成功!";
InBlock.gif                        
//strInfo += "<br />地址:<font color=red> " + strFilePath +" </font>";
InBlock.gif
                        strInfo += "<br />文件地址:<font color=red> " + strUrl +" </font>";
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public string GetInfo()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return strInfo;
ExpandedSubBlockEnd.gif            }

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

InBlock.gif                
return strAppPath;
ExpandedSubBlockEnd.gif            }

InBlock.gif    
ExpandedBlockEnd.gif        }


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

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

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

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

转载于:https://www.cnblogs.com/KenBlove/articles/463299.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值