asp.net 多文件上传

 

Asp.Net 2.0 实现多文件上传的方法
【摘要】
多文件上传的方法其实很简单,在页面上添加多个html文件上传控件,就可在代码中用如下语句System.Web.HttpContext.Current.Request.Files来取得页面中的所有文件上传控年对象,然后调用 Files对象的SaveAs就可将多个文件上传上去,跟单文件上传没有多大区别。
【全文】

如下代码示例,可将多个文件上传到服务器,并显示在表格中和列表框中,并可将列表框中选择的文件从服务器删除掉。
[页面文件HTML]
<%@ 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">
<script language="JavaScript">
function addFile()
{
     //添加文件上传Html组件
var str ='<input type="file" name="File" class="FileUpStyle" /><br>'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
function Button1_onclick() {
     //重置文件上传Html组件
     var str='<input type="file" name="File"class="FileUpStyle" id="File1" /> ';
     str=str+'<br>';
     document.getElementById('MyFile').innerHTML=str;
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
     <title>多文件上传示例</title>
     <STYLE TYPE="text/css" MEDIA=screen>
         <!--

.FileUpStyle {
font-size: 12px;
font-weight: lighter;
font-variant: normal;
border: 1px solid #006699;
width: 250px;
}
         -->
     </STYLE>
</head>
<body style="font-size: 9pt; color: #000066;">
     <form id="form1" runat="server" enctype="multipart/form-data">
         多文件上传示例<br />
            <input type="button" value="增加" οnclick="addFile()" style="border-right: #6699cc 1px solid; border-top: #6699cc 1px solid; font-size: 9pt; border-left: #6699cc 1px solid; width: 60px; border-bottom: #6699cc 1px solid">
           <input type="button" value="重置" style="border-right: #6699cc 1px solid; border-top: #6699cc 1px solid; font-size: 9pt; border-left: #6699cc 1px solid; width: 60px; border-bottom: #6699cc 1px solid; height: 20px" id="Button1" language="javascript" οnclick="return Button1_onclick()">
           <asp:Button Runat="server" Text="上传" ID="Upload" OnClick="Upload_Click1" BorderColor="Desktop" BorderWidth="1px" Height="20px" Width="60px" ></asp:Button>
         <asp:Button ID="btn_Refresh" runat="server" BorderColor="Desktop" BorderWidth="1px" Height="20px"
             Text="刷新目录" Width="60px" OnClick="btn_Refresh_Click" /><br />
         <div id="MyFile">
          <input name="File" type="file" class="FileUpStyle" id="File1"/>
         <br />
         </div>
         已上传的文件:<asp:LinkButton ID="btn_del" runat="server" OnClick="btn_del_Click" OnClientClick="return confirm('确认要网站上删除此文件吗?')">删除选择的文件</asp:LinkButton><br />
         <asp:DropDownList ID="drp1" runat="server" Width="250px">
         </asp:DropDownList>
         &nbsp;&nbsp;
         <asp:Table ID="tableDirInfo" runat="server" ForeColor="#000040">
         </asp:Table>
     </form>
</body>
</html>
[程序代码文件CODE]
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;

public partial class _Default : System.Web.UI.Page
{

     protected void Page_Load(object sender, EventArgs e)
     {
     }
     protected void Upload_Click1(object sender, EventArgs e)
     {

         HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;

         for (int i = 0; i < _files.Count; i++)
         {
             string ShortFileName=_files[i].FileName.Substring(_files[i].FileName.LastIndexOf("file://%22)+1/);
             if (ShortFileName != "")
             {
                 _files[i].SaveAs(Server.MapPath("~/Files/" + ShortFileName));
                 //Page.Response.Write("文件名:[" + ShortFileName + "]上传成功!<br>");              
             }
            
         }
     }
     private void ShowFileList()
     {
         string strCurDir, FileName, FileExt;
         //文件大小
         long FileSize;
         //最后修改时间;
         DateTime FileModify;

         //初始化时,默认为当前页面所在的目录
         strCurDir = Server.MapPath("Files");

         FileInfo fi;
         DirectoryInfo dir;
         TableCell td;
         TableRow tr;
         tr = new TableRow();
         //动态添加单元格内容
         td = new TableCell();
         td.Controls.Add(new LiteralControl("文件名"));
         tr.Cells.Add(td);
         td = new TableCell();
         td.Controls.Add(new LiteralControl("文件类型"));
         tr.Cells.Add(td);
         td = new TableCell();
         td.Controls.Add(new LiteralControl("文件大小"));
         tr.Cells.Add(td);
         td = new TableCell();
         td.Controls.Add(new LiteralControl("最后修改时间"));
         tr.Cells.Add(td);

         tableDirInfo.Rows.Add(tr);
         //针对当前目录建立目录引用对象
         DirectoryInfo dirInfo = new DirectoryInfo(strCurDir);
        
         //清除Table中所有行
         for (int j = 0; j < tableDirInfo.Rows.Count; j++)
             tableDirInfo.Rows.RemoveAt(j);
         drp1.Items.Clear();
        
         //循环判断当前目录下的文件和目录
         foreach (FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
         {
             FileName = "";
             FileExt = "";
             FileSize = 0;
             //如果是文件
             if (fsi is FileInfo)
             {
                 fi = (FileInfo)fsi;
                 //取得文件名
                 FileName = fi.Name;
                 drp1.Items.Add(FileName);

                 //取得文件的扩展名
                 FileExt = fi.Extension;
                 //取得文件的大小
                 FileSize = fi.Length;
                 //取得文件的最后修改时间
                 FileModify = fi.LastWriteTime;
             }
             else//否则是目录
             {
                 dir = (DirectoryInfo)fsi;
                 //取得目录名
                 FileName = dir.Name;
                 //取得目录的最后修改时间
                 FileModify = dir.LastWriteTime;
                 //设置文件的扩展名为"文件夹"
                 FileExt = "文件夹";
             }
             //动态添加表格内容
             tr = new TableRow();
             td = new TableCell();
             td.Controls.Add(new LiteralControl(FileName));
             tr.Cells.Add(td);
             td = new TableCell();
             td.Controls.Add(new LiteralControl(FileExt));
             tr.Cells.Add(td);
             td = new TableCell();
             td.Controls.Add(new LiteralControl(FileSize.ToString() + "字节"));
             tr.Cells.Add(td);
             td = new TableCell();
             td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));
             tr.Cells.Add(td);
             tableDirInfo.Rows.Add(tr);
         }
     }
     protected void btn_Refresh_Click(object sender, EventArgs e)
     {
         //刷新目录列表
         ShowFileList();
     }
     protected void btn_del_Click(object sender, EventArgs e)
     {
         //删除选择的文件
         if (drp1.Items.Count != 0)
         {
             System.IO.File.Delete(Server.MapPath("Files/" + drp1.SelectedItem.Text));
             ShowFileList();
         }
     }
}


UpLoad.aspx

<% @ Page language = " c# "  Codebehind = " UpLoad.aspx.cs "  AutoEventWireup = " false "  Inherits = " WebPortal.Upload "   %>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"  >
< HTML >
  
< HEAD >
    
< title > 多文件上传 </ title >
    
< script  language ="JavaScript" >
    
function  addFile()
    {
        
var  str  =  ' < INPUT type = " file "  size = " 50 "  NAME = " File " > '
        document.getElementById('MyFile').insertAdjacentHTML(
" beforeEnd " ,str)
    }
    
</ script >
  
</ HEAD >
  
< body >
    
< form  id ="form1"  method ="post"  runat ="server"  enctype ="multipart/form-data" >
      
< div  align ="center" >
        
< h3 > 多文件上传 </ h3 >
        
< id ="MyFile" >< INPUT  type ="file"  size ="50"  NAME ="File" ></ P >
        
< P >
          
< input  type ="button"  value ="增加(Add)"  onclick ="addFile()" >
          
< input  onclick ="this.form.reset()"  type ="button"  value ="重置(ReSet)" >
          
< asp:Button  Runat ="server"  Text ="开始上传"  ID ="UploadButton" ></ asp:Button >
        
</ P >
        
< P >
        
< asp:Label  id ="strStatus"  runat ="server"  Font-Names ="宋体"  Font-Bold ="True"  Font-Size ="9pt"  
          Width
="500px"  BorderStyle ="None"  BorderColor ="White" ></ asp:Label >
        
</ P >  
      
</ div >
    
</ form >
  
</ body >
</ HTML >



UpLoad.aspx.cs

using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;

namespace  WebPortal
{
  
///   <summary>
  
///  UpLoad 的摘要说明。
  
///  实现多文件上传
  
///   </summary>
   public   class  Upload : System.Web.UI.Page
  {
    
protected  System.Web.UI.WebControls.Button UploadButton;
    
protected  System.Web.UI.WebControls.Label strStatus;

    
private   void  Page_Load( object  sender, System.EventArgs e)
    {
      
///  在此处放置用户代码以初始化页面
       if  ( this .IsPostBack)  this .SaveImages();
    }

    
private  Boolean SaveImages()
    {
      
/// '遍历File表单元素
      HttpFileCollection files   =  HttpContext.Current.Request.Files;

      
///  '状态信息
      System.Text.StringBuilder strMsg  =   new  System.Text.StringBuilder();
      strMsg.Append(
" 上传的文件分别是:<hr color=red> " );
      
try
      {
        
for ( int  iFile  =   0 ; iFile  <  files.Count; iFile ++ )
        {
          
/// '检查文件扩展名字
          HttpPostedFile postedFile  =  files[iFile];
          
string  fileName, fileExtension;
          fileName 
=  System.IO.Path.GetFileName(postedFile.FileName);
          
if  (fileName  !=   "" )
          {
            fileExtension 
=  System.IO.Path.GetExtension(fileName);
            strMsg.Append(
" 上传的文件类型: "   +  postedFile.ContentType.ToString()  +   " <br> " );
            strMsg.Append(
" 客户端文件地址: "   +  postedFile.FileName  +   " <br> " );
            strMsg.Append(
" 上传文件的文件名: "   +  fileName  +   " <br> " );
            strMsg.Append(
" 上传文件的扩展名: "   +  fileExtension  +   " <br><hr> " );
            
/// '可根据扩展名字的不同保存到不同的文件夹
            
/// 注意:可能要修改你的文件夹的匿名写入权限。
            postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath( " images/ " +  fileName);
          }
        }
        strStatus.Text 
=  strMsg.ToString();
        
return   true ;
      }
      
catch (System.Exception Ex)
      {
        strStatus.Text 
=  Ex.Message;
        
return   false ;
      }
    }
  
#region  Web 窗体设计器生成的代码
  
override   protected   void  OnInit(EventArgs e)
  {
  
//
  
//  CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
  
//
  InitializeComponent();
  
base .OnInit(e);
  }

  
///   <summary>
  
///  设计器支持所需的方法 - 不要使用代码编辑器修改
  
///  此方法的内容。
  
///   </summary>
   private   void  InitializeComponent()
  {    
    
this .ID  =   " Upload " ;
    
this .Load  +=   new  System.EventHandler( this .Page_Load);

  }
  
#endregion
  }
}



文件的上传下载是我们在实际项目开发过程中经常需要用到的技术,这里给出几种常见的方法,本文主要内容包括:
1、如何解决文件上传大小的限制
2、以文件形式保存到服务器
3、转换成二进制字节流保存到数据库以及下载方法
4、上传Internet上的资源

第一部分:
    首先我们来说一下如何解决ASP.NET中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改WEB.Config文件来自定义最大文件大小,如下:

< httpRuntime  executionTimeout ="300"  maxRequestLength ="40960"  useFullyQualifiedRedirectUrl ="false" />

这样上传文件的最大值就变成了4M,但这样并不能让我们无限的扩大MaxRequestLength的值,因为ASP.NET会将全部文件载入内存后,再加以处理。解决的方法是利用隐含的HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法从IIS为ASP.NET建立的pipe里分块读取数据。实现方法如下:

IServiceProviderprovider = (IServiceProvider)HttpContext.Current;
HttpWorkerRequestwr
= (HttpWorkerRequest)provider.GetService( typeof (HttpWorkerRequest));
byte []bs = wr.GetPreloadedEntityBody();
.
if ( ! wr.IsEntireEntityBodyIsPreloaded())
{
intn
=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}

}

这样就可以解决了大文件的上传问题了。

第二部分:
    下面我们来介绍如何以文件形式将客户端的一个文件上传到服务器并返回上传文件的一些基本信息
首先我们定义一个类,用来存储上传的文件的信息(返回时需要)。

public   class  FileUpLoad
{
   
public FileUpLoad()
   
{

   }

/// <summary>
        
/// 上传文件名称
        
/// </summary>

        public string FileName
        
{
            
get
            
{
                
return fileName;
            }

            
set
            
{
                fileName 
= value;
            }

        }

        
private string fileName;

        
/// <summary>
        
/// 上传文件路径
        
/// </summary>

        public string FilePath
        
{
            
get
            
{
                
return filepath;
            }

            
set
            
{
                filepath 
= value;
            }

        }

        
private string filepath;

        
        
/// <summary>
        
/// 文件扩展名
        
/// </summary>

        public string FileExtension
        
{
            
get
            
{
                
return fileExtension;
            }

            
set
            
{
            
                fileExtension 
= value;
            }

                
        }

        
private string fileExtension;
}

另外我们还可以在配置文件中限制上传文件的格式(App.Config):

<? xml version="1.0" encoding="gb2312"  ?>
< Application >     
    
< FileUpLoad >
       
< Format > .jpg|.gif|.png|.bmp </ Format >
    
</ FileUpLoad >
</ Application >


这样我们就可以开始写我们的上传文件的方法了,如下:

public  FileUpLoad UpLoadFile(HtmlInputFile InputFile, string  filePath, string  myfileName, bool  isRandom)
        
{
            
            FileUpLoad fp 
= new FileUpLoad();

            
string fileName,fileExtension;
            
string saveName;
            
            
//
            
//建立上传对象
            
//
            HttpPostedFile postedFile = InputFile.PostedFile;

            fileName        
= System.IO.Path.GetFileName(postedFile.FileName);
            fileExtension    
= System.IO.Path.GetExtension(fileName);
            
            
//
            
//根据类型确定文件格式
            
//
            AppConfig app = new AppConfig();
            
string format = app.GetPath("FileUpLoad/Format");


            
//
            
//如果格式都不符合则返回
            
//
            if(format.IndexOf(fileExtension)==-1)
            
{
                
throw new ApplicationException("上传数据格式不合法");
            }

                
            
//
            
//根据日期和随机数生成随机的文件名
            
//
            if(myfileName != string.Empty)
            
{
                fileName 
= myfileName;            
            }


            
if(isRandom)
            
{
                Random objRand 
= new Random();
                System.DateTime date 
= DateTime.Now;
                
//生成随机文件名
                saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() 

                    
+ date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
                fileName 
= saveName + fileExtension;
            }

            
            
string phyPath = HttpContext.Current.Request.MapPath(filePath);


            
//判断路径是否存在,若不存在则创建路径
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            
if(!upDir.Exists)
            
{
                upDir.Create();
            }


            
//
            
//保存文件
            
//
            try
            
{
                postedFile.SaveAs(phyPath 
+ fileName);

                fp.FilePath 
=  filePath  + fileName;
                fp.FileExtension 
= fileExtension;
                fp.FileName 
= fileName;
            }

            
catch
            
{
                
throw new ApplicationException("上传失败!");
            }



            
//返回上传文件的信息
            return fp;
        
        
        }

然后我们在上传文件的时候就可以调用这个方法了,将返回的文件信息保存到数据库中,至于下载,就直接打开那个路径就OK了。

第三部分:
    这里我们主要说一下如何以二进制的形式上传文件以及下载。首先说上传,方法如下:

public   byte [] UpLoadFile(HtmlInputFile f_IFile)
{
         
//获取由客户端指定的上传文件的访问
         HttpPostedFile upFile=f_IFile.PostedFile;
         
//得到上传文件的长度
                int upFileLength=upFile.ContentLength; 
         
//得到上传文件的客户端MIME类型
                string contentType = upFile.ContentType;
                
byte[] FileArray=new Byte[upFileLength];
 
                Stream fileStream
=upFile.InputStream; 
                
                fileStream.Read(FileArray,
0,upFileLength);
        
        
return FileArray;

}


这个方法返回的就是上传的文件的二进制字节流,这样我们就可以将它保存到数据库了。下面说一下这种形式的下载,也许你会想到这种方式的下载就是新建一个aspx页面,然后在它的Page_Load()事件里取出二进制字节流,然后再读出来就可以了,其实这种方法是不可取的,在实际的运用中也许会出现无法打开某站点的错误,我一般采用下面的方法:
首先,在Web.config中加入:

< add  verb ="*"  path ="openfile.aspx"  type ="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web" />


这表示我打开openfile.aspx这个页面时,系统就会自动转到执行RuixinOA.Web.BaseClass.OpenFile 这个类里的方法,具体实现如下:

using  System;
using  System.Data;
using  System.Web;
using  System.IO;
using  Ruixin.WorkFlowDB;
using  RXSuite.Base;
using  RXSuite.Component;
using  RuixinOA.BusinessFacade;

namespace  RuixinOA.Web.BaseClass
{
    
/// <summary>
    
/// NetUFile 的摘要说明。
    
/// </summary>

    public class OpenFile : IHttpHandler
    
{
        
public void ProcessRequest(HttpContext context) 
        
{
            
            
//从数据库中取出要下载的文件信息
            RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
            EntityData data 
= os.GetFileDetail(id);

            
if(data != null && data.Tables["RX_OA_File"].Rows.Count > 0)
            
{
                DataRow dr 
= (DataRow)data.Tables["RX_OA_File"].Rows[0];

                context.Response.Buffer 
= true;
                context.Response.Clear();
                context.Response.ContentType 
= dr["CContentType"].ToString(); 
                context.Response.AddHeader(
"Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
                context.Response.BinaryWrite((Byte[])dr[
"CContent"]);
                context.Response.Flush();
                context.Response.End();
            }

                        

        }


        
public bool IsReusable 
        


            
get return true;} 
        }

    }

}


执行上面的方法后,系统会提示用户选择直接打开还是下载。这一部分我们就说到这里。

第四部分:

    这一部分主要说如何上传一个Internet上的资源到服务器。前面我们有一篇文章详细介绍了使用方法,这里我不再多说。


将动态页面转化成二进制字节流

最近在做办公自动化系统的工作流部分时中有这样的要求,在每个流程的归档环节,要求将该流程的标签页面直接用二进制保存到数据库(因为我们面向的客户是公安局,出于安全性和数据备份的简便性考虑)。由于我们一般的文件上传都是一个物理上存在的文件,而这里的流程标签页面是根据ID号动态生成的,刚开始我用了一个比较笨的方法,思路是:先将这个页面保存到服务器的硬盘上,然后再上传到数据库中。方法实现如下:

 

 
 
HttpContext.Current.Response.AppendHeader( " Content-Disposition " , " attachment;filename=upload.doc " );
HttpContext.Current.Response.Charset 
= "" ;
HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.GetEncoding( " utf-8 " );
HttpContext.Current.Response.ContentType 
= " application/msword " ;
pn_upload.Page.EnableViewState 
= false ;
System.IO.StringWriter  tw 
=   new  System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw 
=   new  System.Web.UI.HtmlTextWriter(tw);
pn_upload.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();

这样页面就以Word格式保存到计算机上了,然后执行上传到数据库的操作,这样也能实现客户的需求,但给人的感觉总是怪怪的,肯定是个下下策了。

今天无意之中在网上看到了一篇文章,原文来自:http://wuchang.cnblogs.com/archive/2004/08/14/33394.aspx,可以很好的解决这个问题。

首先需要引用 System.Net 这个命名空间,然后操作如下:

 
 
HttpWebRequest hwq  =  (HttpWebRequest)WebRequest.Create( " http://localhost/pwtest/webform1.aspx " );
HttpWebResponse hwr 
=  (HttpWebResponse)hwq.GetResponse();
byte [] bytes  =   new   byte [hwr.ContentLength];
Stream stream 
=  hwr.GetResponseStream();
stream.Read(bytes,
0 ,Convert.ToInt32(hwr.ContentLength));
// HttpContext.Current.Response.BinaryWrite(bytes);

HttpWebRequest 可以从Internet上读取文件,因此可以很好的解决这个问题。

以上代码在VS2003中调试通过。


文件上传

一.   在Form中一定要将encType设为"multipart/form-data":
<form id="WebForm3" method="post" encType="multipart/form-data" runat="server" >

二.   判断是否有文件上传了:
当用户没有选择任何要上传的文件,即HtmlInputFile控件中的文本框为空时点击了上传按钮后,在服务端得到的File1.PostedFile对象不是null,而是有对象的,所以不能用(File1.PostedFile == null)来判断是否上传了文件,用(File1.PostedFile.ContentLength != 0)来判断比较好

三.   判断上传文件MIMIE类型:
文件上传后可以用File1.PostedFile.ContentType来读取这个文件的MIMIE类型,这个MIMIE类型是系统通过上传文件的后缀名来获得的。

四.   保存上传的文件:

1.    文件可以通过File1.PostedFile.SaveAs(path) //path是服务器上的物理路径,来保存文件。

if(File1.PostedFile.ContentLength != 0)

{

    StringBuilder myStr = new StringBuilder();

    myStr.Append("文件名称:" + File1.PostedFile.FileName);

    myStr.Append("<br>");

    myStr.Append("文件类型:" + File1.PostedFile.ContentType);

    myStr.Append("<br>");

    myStr.Append("文件长度:" + File1.PostedFile.ContentLength.ToString());

    myStr.Append("<br>");

   

    string path = Server.MapPath("./"); //当前路径

    string fileName = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf('//')+1);

    path += fileName;

    if(File.Exists(path) == true)

    {

       Label1.Text = "服务器上已经有了你正在上传的文件:" + fileName;

       return;

    }

    File1.PostedFile.SaveAs(path);



    myStr.Append("保存完毕!");

    myStr.Append("<br>");

    Label1.Text = myStr.ToString();

}

else

{

    Label1.Text = "你没有选择要上载的文件或者上传的文件长度为0!";

}


2.    文件也可以通过二进制的读取后存放到数据库的二进制的字段中:
byte[] fileCont = new byte[File1.PostedFile.ContentLength];
File1.PostedFile.InputStream.Read(fileCont,0, File1.PostedFile.ContentLength);
然后将此字节数组fileCont赋给数据库的二进制字段的参数,写到数据库中。



文件下载

一.   服务端通过Response输出相应的HTTP Response Headers信息,和要下载的文件的数据来把文件发送到客户端,HTTP Response Headers表现在html文件中是下面的形式:
<meta http-equiv="Content-Type" content="text/htm ">
http-equiv表示是Headers的名称,content表示这个Headers的值

二.   首先,要输出文件的MIME类型:
Page.Response.AddHeader( "Content-Type", “MIME类型” ); 

三.   其次,要输出下载的文件的打开位置和文件名:
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName );
content-disposition 的 HTTP response header 允许指定文档表示的信息。使用这种 header ,你就可以将文档指定成单独打开(而不是在浏览器中打开),还可以根据用户的操作来显示。如果用户要保存文档,你还可以为该文档建议一个文件名。这个建议名称会出现在 Save As 对话框的“文件名”栏中。
打开位置:
attachment ―― 表示作为附件发送到客户端,客户端将单独打开此文件。
inline ―― 表示将在浏览器中打开这个文件。
文件名:
filename ―― 表示发送到客户端文件的文件名。

四.   准备发送到客户端的文件数据:

1.    先将不同类型来源的数据转成byte类型的数组,再通过Response.BinaryWrite方法发送到客户端:

1.1.   读取文件来获得byte数组: string FileName; //生成或获取要发送到客户端的文件名

string filePath = Server.MapPath("./") + FileName; //假设文件在当前目录下

if(File.Exists(filePath) == false)

{

    //服务器上没有这个文件

    return;

}

FileStream myFile = File.OpenRead(filePath); //读取文件进入FileStream

byte[] fileCont = new byte[myFile.Length];

myFile.Read(fileCont,0,(int)myFile.Length);  //将文件流中的内容转成byte数组


1.2.   在数据库的二进制字段中读取: //从url获取图片的id

string ImageId = Request.QueryString["img"];

//构建查询语句

string sqlText = "SELECT img_data, img_contenttype FROM Image WHERE img_pk = " + ImageId;

SqlConnection connection = new SqlConnection( ConfigurationSettings.AppSettings["DSN"].ToString() );

SqlCommand command = new SqlCommand( sqlText, connection);

connection.Open();

SqlDataReader dr = command.ExecuteReader();

if ( dr.Read())

{

    byte[] fileCont = (byte[]) dr["img_data"] ;

}

connection.Close();


1.3.   从internet上读取文件: HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create( "http://www.via.com/aa.xls ");

HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();

Stream readStream = myWebResponse.GetResponseStream();

          

byte[] bytes = new byte[readStream.Length];

bytes = readStream.Read(bytes,0,readStream.Length);


通过上述三种方法获得的文件内容的byte数组就可以用来输出了:
Page.Response.BinaryWrite(fileCont);

Page.Response.End();



2.    直接读取文件输出: string FileName; //生成或获取要发送到客户端的文件名

string filePath = Server.MapPath("./") + FileName; //假设文件在当前目录下

if(File.Exists(filePath) == false)

{

    //服务器上没有这个文件

    return;

}

Page.Response.Clear();

Page.Response.AddHeader( "Content-Type", "image/gif" ); //根据MIME的不同设置

Page.Response.AddHeader("Content-Disposition", "inline;filename=" + filePath);

Page.Response.WriteFile(filePath);

Page.Response.End();



内容结束//



无刷新上传主要的HTML代码(upload.html):

<! 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 >
< title > AjaxUpload </ title >
< meta  http-equiv ="Content-Type"  content ="text/html; charset=utf-8"   />
< script  type ="text/javascript"  src ="scripts/jquery.js" ></ script >
< script  type ="text/javascript"  src ="scripts/interface.js" ></ script >
< style  type ="text/css"  media ="all" >
*
{
    margin
: 0 ;
    padding
: 0 ;
}

img
{ border : none ; }

ul
{
    list-style-type
: none ;
}

ul li
{
    padding
: 2px 4px ;
}

body
{
    font-family
:  宋体, 黑体,verdana, Arial ;
    font-size
: 12px ;
    color
: #333 ;
    background
: #DDDDDD ;
    margin
: 30px ;
    padding
: 0 ;
}

.box
{
    border
: 1px solid #CCC ;
    background
: #FFF ;
    padding
: 8px ;
    margin
: 5px ;
    clear
: both ;
}

.title 
{
    background
: #F0F0F0 ; padding : 5px ;
    font-weight
: bold ;
}

.tooltip
{
    background
: #F0F0F0 ;
    border-color
: #bbb ;
}

.tooltip h1 
{
    color
: #A8DF00 ;
    font-family
:  微软雅黑,黑体,宋体,verdana, Arial ;
}

.titlebutton
{
    float
: right ;
}

.uploading
{
    background
: #FFF ;
    color
: #444 ;
    text-align
: left ;
    width
: 500px ;
    padding
: 4px ;
}

.image
{
    border
: 1px solid #ddd ;
    margin
: 2px ;
    padding
: 1px ;
    display
: inline ;
    width
: 300px ;
}

.uploadcontrol 
{
    margin
: 4px 0 ;
    border-bottom
: 1px solid #F0F0F0 ;
}
</ style >
< script  type ="text/javascript" >
    
     $(document).ready(
function (){          
          
for ( var  i = 0 ;i < 5 ;i ++ )
          {
             uploadcreate($(
" #uploadbox " ),i);
          }
    });
     
     
var  hideDiv  =   function (idName){
         $(
" # " + idName).fadeOut( " fast " );
     };
     
     
// 是否显示上传后的图片
      var  isshowpic  =   true ;  
     
var  uploadshowpic  =   function (el){
         isshowpic 
=   ! (isshowpic);
         
if (isshowpic)
         {
             el.html(
" 图片显示关闭 " );
         }
         
else
         {
             el.html(
" 图片显示开启 " );
         }
     };
     
     
// 载入中的GIF动画
     var  loadingUrl  =   " images/ajax-loader.gif " ;
    
    
// 选择文件后的事件,iframe里面调用的
     var  uploading  =   function (imgsrc,itemid){
        
var  el  =  $( " #uploading " + itemid);
        $(
" #ifUpload " + itemid).fadeOut( " fast " );
        el.fadeIn(
" fast " );
        el.html(
" <img src=' " + loadingUrl + " ' align='absmiddle' /> 上传中 " );
        
return  el;
    };
    
    
// 重新上传方法    
     var  uploadinit  =   function (itemid){
        currentItemID 
++ ;
        $(
" #uploading " + itemid).fadeOut( " fast " , function (){
             $(
" #ifUpload " + itemid).fadeIn( " fast " );
             $(
" #panelViewPic " + itemid).fadeOut( " fast " );
        });
               
    };
    
    
// 上传时程序发生错误时,给提示,并返回上传状态
     var  uploaderror  =   function (itemid){
        alert(
" 程序异常, " + itemid + " 项上传未成功。 " );
        uploadinit();
    };
    
    
// 上传成功后的处理
     var  uploadsuccess  =   function (newpath,itemid){
        $(
" #uploading " + itemid).html( " 文件上传成功. <a href='javascript:void(0);' οnclick='uploadinit( " + itemid + " );'>[重新上传]</a> " );
        
if (isshowpic)
        {
            $(
" #panelViewPic " + itemid).html( " <a href=' " + newpath + " ' title='点击查看大图' target='_blank'><img src=' " + newpath + " ' alt='' style='width:300px;' /></a> " );        
            $(
" #panelViewPic " + itemid).fadeIn( " fast " );
        }
    };
    
    
    
var  currentItemID  =   0 ;   // 用于存放共有多少个上传控件了
     // 创建一个上传控件
     var  uploadcreate  =   function (el,itemid){
        currentItemID 
++ ;
        
if (itemid  ==   null )
        {
            itemid 
=  currentItemID;
        }  
        
var  strContent  =   " <div class='uploadcontrol'><iframe src=/ " upload.aspx ? id = " +itemid+ " / "  id=/ " ifUpload " +itemid+ " / "  frameborder=/ " no/ "  scrolling=/ " no/ "  style=/ " width:400px; height:28px;/ " ></iframe> " ;
        strContent 
+=   " <div class=/ " uploading/ "  id=/ " uploading " +itemid+ " / "  style=/ " display:none;/ "  ></div> " ;
        strContent 
+=   " <div class=/ " image/ "  id=/ " panelViewPic " +itemid+ " / "  style=/ " display:none;/ " ></div></div> " ;
        el.append(strContent);
    };
     
</ script >

</ head >

< body >

< div  id ="tipbox"  class ="box tooltip" >
    
< href ="#"  onclick ="hideDiv('tipbox');" > [关闭] </ a >
    
< div  class ="content" >
        
< h1 > AjaxUpload - 多文件无刷新上传源代码 v1.0 </ h1 >
        
< p > 作者:李华顺  < href ="http://huacn.cnblogs.com"  target ="_blank" > http://huacn.cnblogs.com </ a ></ p >
    
</ div >  
</ div >
< div  id ="toolbox"  class ="tooltip box" >
    
< href ="#"  onclick ="uploadcreate($('#uploadbox'));" > 添加一个新上传控件 </ a >   < href ="#"  onclick ="uploadshowpic($(this));" > 图片显示关闭 </ a >
</ div >
< div  id ="uploadbox"  class ="box" >
    
</ div >

</ body >

</ html >


上传功能的页面代码(upload.aspx):

<% @ Page Language = " C# "  AutoEventWireup = " true "  CodeFile = " upload.aspx.cs "  Inherits = " upload "   %>

<! 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 > 上传 </ title >
    
< meta  http-equiv ="Content-Type"  content ="text/html; charset=utf-8"   />
    
< script  type ="text/javascript"  src ="scripts/jquery.js" ></ script >
    
< script  type ="text/javascript"  src ="scripts/interface.js" ></ script >
    
< style  type ="text/css" >
        *
{  margin : 0 ;  padding : 0 ;   }
        
    
</ style >
    
< script  type ="text/javascript" >
        
        
var  uploadSelect  =   function (el){
            el.fadeOut(
" show " );        
            parent.uploading(document.getElementById(
" <%=file1.ClientID %> " ).value,' <%= itemID  %> ');
            $(
" #<%=frmUpload.ClientID %> " ).submit();
        };
         
    
</ script >
</ head >
< body >
    
< form  runat ="server"  id ="frmUpload"  method ="post"  enctype ="multipart/form-data" >
        
< input  type ="file"  runat ="server"  id ="file1"  size ="40"  onchange ="uploadSelect($(this));"   />         
    
</ form >
</ body >
</ html >


上传功能的服务端代码(upload.aspx.cs)

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.IO;

public  partial  class  upload : System.Web.UI.Page
{
    
string  picPath  =   "" ;
    
string  picServer  =   " /upload " ;
    
protected   string  itemID  =   "" ;
    
protected   void  Page_Load( object  sender, EventArgs e)
    {

        
if  (Request.QueryString[ " id " !=   null )
        {
            itemID 
=  Request.QueryString[ " id " ];
        }
  
        
if  (IsPostBack)
        {
            picPath 
=  Server.MapPath( " //upload " );
            doUpload();
        }
    }

    
protected   void  doUpload()
    {
        
try
        {
            HttpPostedFile file 
=  file1.PostedFile;
            
string  strNewPath  =  GetSaveFilePath()  +  GetExtension(file.FileName);
            file.SaveAs(picPath
+ strNewPath);
            
string  urlPath  =  picServer  +  strNewPath;
            urlPath 
=  urlPath.Replace( " // " " / " );
            WriteJs(
" parent.uploadsuccess(' "   +  urlPath  +   " ',' "   +  itemID  +   " ');  " );
            
        }
        
catch  (Exception ex)
        {
            WriteJs(
" parent.uploaderror(); " );            
        }
    }

    
private   string  GetExtension( string  fileName)
    {
        
try
        {
            
int  startPos  =  fileName.LastIndexOf( " . " );
            
string  ext  =  fileName.Substring(startPos, fileName.Length  -  startPos);
            
return  ext;
        }
        
catch  (Exception ex)
        {
            WriteJs(
" parent.uploaderror(' "   +  itemID  +   " '); " );
            
return   string .Empty;
        }
    }

    
private   string  GetSaveFilePath()
    {
        
try
        {
            DateTime dateTime 
=  DateTime.Now;
            
string  yearStr  =  dateTime.Year.ToString(); ;
            
string  monthStr  =  dateTime.Month.ToString();
            
string  dayStr  =  dateTime.Day.ToString();
            
string  hourStr  =  dateTime.Hour.ToString();
            
string  minuteStr  =  dateTime.Minute.ToString();
            
string  dir  =  dateTime.ToString( @" //yyyyMMdd " );
            
if  ( ! Directory.Exists(picPath  +  dir))
            {
                Directory.CreateDirectory(picPath 
+  dir);
            }
            
return  dir  +  dateTime.ToString( " yyyyMMddhhmmssffff " );
        }
        
catch  (Exception ex)
        {
            WriteJs(
" parent.uploaderror(); " );
            
return   string .Empty;
        }
    }

    
protected   void  WriteJs( string  jsContent)
    {        
        
this .Page.RegisterStartupScript( " writejs " , " <script type='text/javascript'> " +  jsContent + " </script> " );
    }

}


 


基本上就是这些,重点请看第一部份的代码,主要是JS控件显示,还有一个重点是upload.aspx调用父级页面的方法这些实现。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值