现在的位置: 首页 > 综合 > 正文

asp.net 上传文件方法(内闭式和开放式)

2011年07月28日 ⁄ 综合 ⁄ 共 5610字 ⁄ 字号 评论关闭

1.内闭式(RUNAT SERVER方式)

这种方式是目前大多数人使用的一种,通过事件驱动来实现文件上传处理,Form及File Field需设置为Runat Server


    
/// <summary>
    
/// 上传文件
    
/// </summary>
    
/// <param name="filepathLevel">上传文件的路径层</param>
    
/// <param name="filepath">根目录下文件存在的路径</param>
    
/// <param name="filename">文件名称,默认null</param>
    
/// <param name="fileFormat">文件格式(以,分隔)</param>
    
/// <param name="maxAmount">文件大小(MB计算)</param>
    
/// <param name="fud">上传组件名</param>
    
/// <param name="fileIsExists">是否必需上传</param>
    
/// <returns></returns>
    public static string FileUpload(string filepathLevel, string filepath, string filename, string fileFormat, int maxAmount, FileUpload fud,bool fileIsExists)
    {
        
bool formatStatus = false;
        
string eorrStr = "";
        
string strText = null;
        
string tmpfilepath = System.Web.HttpContext.Current.Server.MapPath(filepathLevel) + filepath;
        
string tmpfilename;
        
if (filename == null)   ///默认名称
        { tmpfilename = DateTime.Now.ToString("yyyyMMddhhmmss"+ DateTime.Now.Millisecond.ToString(); }
        
else
        { tmpfilename 
= filename; }
        
///---------------------------创建文件夹---------------------------
        //HttpContext.Current.Server.MapPath(相对路径):把相对路径转为服务器上的绝对路径。File.Exists(绝对路径):检查是否存在绝对路径指向的文件或目录。
        if (!File.Exists(tmpfilepath))
        {
            System.IO.Directory.CreateDirectory(tmpfilepath);              
//System.IO.Directory.CreateDirectory(文件夹绝对路径):建立绝对路径文件夹。
        }
        
        
///------------------------------写入上传文件--------------------------------
        if (fud.HasFile)
        {
            
try
            {
                
string[] strTpye = fud.FileName.Split('.');
                
if (strTpye.Length > 1)
                {  
                    
int i_split = strTpye.Length - 1;
                    
string format = strTpye[i_split];
                    
string[] sArray = fileFormat.Split(',');
                    
foreach (string i in sArray)
                    {
                        
if (format.ToLower() == i.ToString())
                         {                            
                            formatStatus 
= true;
                            
break;
                        }
                    }
                    
///------------------判断文件格式--------------------
                    if (formatStatus == false)   
                    {
                        eorrStr 
+= "只能上传" + fileFormat + "格式文件";
                    }
                    
///------------------判断大小--------------------
                    int tmpmaxAmount = maxAmount * 1024 * 1024;
                    
if (fud.PostedFile.ContentLength > tmpmaxAmount)  
                    {
                        eorrStr 
+= "上传不能超过" + maxAmount + "MB";
                    }
                    
///------------------写入文件--------------------
                    if (eorrStr == "")
                    {
                        
string savepath = tmpfilepath + tmpfilename + "." + format;
                        
if (!File.Exists(savepath))   //不存在就写入
                        {
                            fud.SaveAs(tmpfilepath 
+ tmpfilename + "." + format);
                        }                         
                        strText 
= filepath + tmpfilename + "." + format;    
                    }
                }
                
else
                {
                    eorrStr 
+= "只能上传" + fileFormat + "格式文件";
                }
                
//  显示文件信息
                
//str += "<br/>Saved As: " + FileUpload1.PostedFile.FileName;
                
//str += "<br/>File Type: " + FileUpload1.PostedFile.ContentType;
                
//str += "<br/>File Length (bytes): " + FileUpload1.PostedFile.ContentLength;
                
//str += "<br/>PostedFile File Name: " + FileUpload1.PostedFile.FileName;
                
// fud.SaveAs(filepath + FileUpload1.FileName);
                
//str += "Uploading file: " + FileUpload1.FileNam
            }
            
catch (Exception ex)
            {
                eorrStr 
+= "<b>Error:</b>Unable to save :" + fud.FileName + "<br/>" + ex.Message;
            }
        }
        
else
        {
            
if (fileIsExists == true)  ///必需上传文件
            {
                eorrStr 
= "No file uploaded.";
            }
        }

        if (eorrStr != "")
        { JScript.Alert(eorrStr); }
        
return strText;        
    }
   

 

 

2.开放式(Submit Form方式)

   该方式可以支持由其他页面提交,自由性较大,代码如下:

 

///upload.aspx

<form name="form1" action="Save.aspx" method="post" enctype="multipart/form-data">
<INPUT type="file" id="File1" name="File1">
<input type="submit" name="submit" value="保存">
</form>

 

 save.aspx


    
private void Page_Load(object sender, System.EventArgs e)
  {
   
if( Request.Files.Count == 0 ) {
    Response.Write(
"<script>alert('请选择上传文件!');</script>");
    Response.End();
    
return;
   }
   System.Web.HttpPostedFile file 
= Request.Files[0];
   String fileName 
= Request["fileName"];
   String save_path 
= "./attached/";
   String ext 
= System.IO.Path.GetExtension( file.FileName ).ToLower();
   Response.Write(ext);
   
if!System.IO.Directory.Exists( Server.MapPath( save_path ) ) )
    System.IO.Directory.CreateDirectory( Server.MapPath( save_path ) );
   
if( ext == ".jpg" || ext == ".gif" || ext == ".bmp" || ext == ".png" ) {
    file.SaveAs( Server.MapPath( save_path 
+ fileName ) );
    Response.Write(
"<script type=\"text/javascript\">parent.KindInsertImage('" + save_path + fileName + "','" + Request["imgWidth"+ "','" + Request["imgHeight"+ "','" + Request["imgBorder"+ "');</script>'");
    Response.End();
   }
   
else {
    Response.Write(
"<script>alert('文件格式不支持!');</script>");
    Response.End();
   }
  }

  

   只需弄清楚 HttpPostedFile和HttpFileCollection这两个对像,写批量文件上传就不是一件难事了。

 

 

抱歉!评论已关闭.