日期:2014-05-19  浏览次数:20597 次

如何实现文件的上传与下载
在Asp.net   中如何把一个word文件上传到服务器上(包括上传到数据库中SQL2000).在客户端可以让客户下载?

------解决方案--------------------
上传文件的代码:
string filePath= " ",fileExtName= " ",mFileName,mPath;
string strContent=txtContent.Text;
string strID=txtID.Text;
strContent = CleanString.htmlInputText( strContent );
string strDate=DateTime.Now.ToString();
if( strContent == String.Empty )
{
Response.Write( " <script> ");
Response.Write( "alert( '请输入进程内容!!! '); ");
Response.Write( " </script> ");
return;
}
if( strContent.Length > 500 )
{
Response.Write( " <script> ");
Response.Write( "alert( '内容太长了..(500字以内)!!! '); ");
Response.Write( " </script> ");
return;
}
if( " "!=fileUp.PostedFile.FileName)
{
//取得文件路径
filePath=fileUp.PostedFile.FileName;
fileExtName=filePath.Substring(filePath.LastIndexOf( ". ")+1);
try
{
//取得与Web服务器上的指定虚拟路径相对应的物理文件路径
mPath=Server.MapPath( "~/UpFile/ ");
//取得文件名
mFileName=filePath.Substring(filePath.LastIndexOf( "\\ ")+1);
if( "doc "!=fileExtName&& "rar "!=fileExtName)
{
Response.Write( " <script> ");
Response.Write( "alert( '对不起,请选择doc或者rar格式的文件!!! '); ");
Response.Write( " </script> ");
}
else
{
string AllPath=mPath+mFileName;
fileUp.PostedFile.SaveAs(mPath+mFileName);
DBConn myDB = new DBConn();
string mySql = "insert into Message(MContent,CourseID,MDate,State,FilePath) values( ' " + strContent + " ', ' " + strID + " ', ' " + strDate + " ', '0 ', ' " + mFileName + " ') ";
myDB.Insert( mySql );
myDB.Close();
Response.Write( " <script> ");
Response.Write( "alert( '上传成功!!! '); ");
Response.Write( " </script> ");
}
}
catch(Exception ex)
{
Response.Redirect( "~/Error.aspx ");
}


下载文件的代码:
DBConn myDB = new DBConn();
string MID=Request.QueryString[ "id "].ToString().Trim();
string mySql = "select FilePath from Message where Message.MID= ' "+MID+ " ' ";
SqlDataReader mydr = myDB.getDataReader( mySql );
string filename= " ";
if( mydr.Read() )
{
filename=mydr[ "FilePath "].ToString();
}
string path = HttpContext.Current.Server.MapPath( "~/UpFile/ ");
Response.Clear();
Response.ContentType = "application/octet-stream ";
Response.AddHeader( "Content-Disposition ", "attachment;FileName= " + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
Response.WriteFile(path+filename);
Response.End();