標籤:class code http tar ext com
//上傳檔案執行個體
if (fileDealer.HasFile)//判斷檔案是否存在
{
string filepath = "";
try
{
string path = fileDealer.FileName;
string filename = path.Split(‘.‘)[0] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");//重名名
if (fileDealer.PostedFile.ContentLength > 50 * 1024 * 1024)
{
Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert(‘上傳檔案不能超過50M!‘);</script>");
return;
}
string serverpath = @"~/Files/Activty/";//存放路徑
string fileExtente = Path.GetExtension(fileDealer.FileName);//副檔名
if (!Directory.Exists(Server.MapPath(serverpath)))
{
Directory.CreateDirectory(Server.MapPath(serverpath));
}
filepath = Path.Combine(serverpath, filename + fileExtente);
fileDealer.SaveAs(Server.MapPath(filepath));
obj.Attachment = filepath;
}
catch (Exception ex)
{
throw ex;
}
}
找了很多的資料,學到了不少有用的東西,最簡單的實現就是使用FileUpload控制項.using System;namespace UpFile { ///
/// upfile 的摘要說明。
///
public class upfile
{
private string path = null;
private string fileType = null;
private int sizes = 0;
///
/// 初始設定變數
///
public upfile()
{
path = @"\uploadimages\"; //上傳路徑
fileType = "jpg|gif|bmp";
sizes = 200; //傳檔案的大小,預設200KB
}///
/// 設定上傳路徑,如:uploadimages\
///
public string Path
{
set
{
path = @"\" + value + @"\";
}
}///
/// 設定上傳檔案大小,單位為KB
///
public int Sizes
{
set
{
sizes = value * 1024;
}
}///
/// 設定上傳檔案的類型,如:jpg|gif|bmp ///
public string FileType
{
set
{
fileType = value;
}
}///
/// 上傳圖片
///
/// 上傳控制項名稱
/// true則以目前時間建立檔案夾,false則為設定的檔案夾
/// 返回上傳圖片的相對路徑
public string fileSaveAs(System.Web.UI.HtmlControls.HtmlInputFile name,bool creatDirectory)
{
try
{
string filePath=null;
//以目前時間修改圖片的名字或建立檔案夾的名字
string modifyFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
//獲得網站的實體路徑
string uploadFilePath = null;
//如果為true則以目前時間建立檔案夾,否則為設定的檔案夾
if(creatDirectory)
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + @"\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + @"\";
}
else
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + path;
}
//獲得檔案的上傳的路徑
string sourcePath=name.Value.Trim();
//判斷上傳檔案是否為空白
if(sourcePath == "" || sourcePath == null)
{
message("您沒有上傳資料呀,是不是搞錯了呀!");
return null;
}
//獲得副檔名
string tFileType = sourcePath.Substring(sourcePath.LastIndexOf(".")+1);
//獲得上傳檔案的大小
long strLen = name.PostedFile.ContentLength;
//分解允許上傳檔案的格式
string[] temp = fileType.Split(‘|‘);
//設定上傳的檔案是否是允許的格式
bool flag = false;
//判斷上傳檔案大小
if(strLen >= sizes)
{
message("上傳的圖片不能大於" + sizes + "KB");
return null;
}
//判斷上傳的檔案是否是允許的格式
foreach(string data in temp)
{
if(data == tFileType)
{
flag = true ;
break;
}
}
//如果為真允許上傳,為假則不允許上傳
if(!flag)
{
message("目前本系統支援的格式為:"+fileType);
return null;
}
System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo(uploadFilePath);
//判斷檔案夾否存在,不存在則建立
if(!dir.Exists)
{
dir.Create();
}
filePath = uploadFilePath + modifyFileName + "." + tFileType;
name.PostedFile.SaveAs(filePath);
filePath = path + modifyFileName + "." + tFileType; return filePath; }
catch
{
//異常
message("出現未知錯誤!");
return null;
}
}private void message(string msg,string url)
{
System.Web.HttpContext.Current.Response.Write(" alert(‘"+msg+"‘);window.location=‘"+url+"‘ ");
}private void message(string msg)
{
System.Web.HttpContext.Current.Response.Write(" alert(‘"+msg+"‘); ");
}
}
}--------------------------------------------------------------------------------
1. C#實現Web檔案的上傳
在Web編程中,我們常需要把一些本地檔案上傳到Web伺服器上,上傳後,使用者可以通過瀏覽器方便地瀏覽這些檔案,應用十分廣泛。 那麼使用C#如何?檔案上傳的功能呢?下面筆者簡要介紹一下。 首先,在你的Visual C# web project 中增加一個上傳用的Web Form,為了要上傳檔案,需要在ToolBox中選擇HTML類的File Field控制項,將此控制項加入到Web Form中,然而此時該控制項還不是服務端控制項,我們需要為它加上如下一段代碼:<INPUT&NBSP;ID=UPLOADFILE1&NBSP;TYPE=FILE&NBSP;SIZE=49&NBSP;RUNAT="SERVER">,這樣它就成為服務端控制項了,如果需要同時上傳數個檔案時,我們可以相應增加此控制項。 需要注意的是代碼中一定要把<form>的屬性設定成為:<form method=post encType=multipart/ form-data runat="server">
如果沒有這個屬性,就不能實現上傳。 然後在此Web Form中增加一個Web Form類的Button,雙擊Button添加如下代碼://上傳圖片的程式段
DateTime now = DateTime.Now ;
//取現在時間到DataTime類的對象now中
string strBaseLocation = "D:\\web\\FC\\pic\\";
//這是檔案將上傳到的伺服器的絕對目錄
if (uploadfile1.PostedFile.ContentLength != 0) //判斷選取對話方塊選取的檔案長度是否為0
{
uploadfile1.PostedFile.SaveAs(strBaseLocation+now.DayOfYear.ToString()+uploadfile1.PostedFile.ContentLength.ToString()+".jpg");
//執行上傳,並自動根據日期和檔案大小不同為檔案命名,確保不重複
Label1.Text="圖片1已經上傳,檔案名稱為:"+now.DayOfYear.ToString()+uploadfile1.PostedFile.ContentLength.ToString()+".jpg";
navigator.Insert(System.Xml.TreePosition.After, XmlNodeType.Element,"pic1","","") ;
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Text,"pic1","","") ;
navigator.Value= now.DayOfYear.ToString()+uploadfile1.PostedFile.ContentLength.ToString()+".jpg" ;
navigator.MoveToParent() ;
}
上面的代碼用於筆者開發的一個使用XML檔案儲存體新聞資訊的系統中,後面幾句代碼作用是寫上傳檔案資訊到XML檔案中。如果要上傳其他類型檔案,只需要將jpg改為相應類型的尾碼名即可,如改為doc即可上傳Word檔案,瀏覽器即可直接瀏覽上傳的Word檔案。 【注意事項】 1. 上傳檔案不可以無限大; 2. 要注意IIS的安全性方面的配合; 3. 用Visual Studio 的安裝項目做安裝程式的時候,請注意安裝程式所在的絕對路徑問題; 4. 注意檔案上傳後的重名問題。
--------------------------------------------------------------------------------2. C#實現Web檔案的上傳using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Configuration;
using System.Drawing;namespace zhuanti
{
/// <summary>
/// 這是一個用於玩家投稿中實現玩家上傳檔案功能中用到的相應的函數的功能模組
/// </summary>
public class FileUpload
{
public enum File //定義一個人用於存放玩家上傳檔案資訊的一個數組
{
FILE_SIZE , //大小
FILE_POSTNAME, //類型(檔案尾碼名)
FILE_SYSNAME , //系統名
FILE_ORGINNAME, //原來的名字
FILE_PATH //檔案路徑
}
private static Random rnd = new Random(); //擷取一個隨機數public static string[] UploadFile(HtmlInputFile file,string Upload_Dir) //實現玩家檔案上傳功能的主函數
{
string[] arr = new String[5];
string FileName = GetUniquelyString(); //擷取一個不重複的檔案名稱
string FileOrginName = file.PostedFile.FileName.Substring(file.PostedFile.FileName.LastIndexOf("\\")+1);//擷取檔案的原始名
if(file.PostedFile.ContentLength<=0)
{ return null; }
string postFileName;
string FilePath = Upload_Dir.ToString();
string path = FilePath + "\\";
try
{
int pos = file.PostedFile.FileName.LastIndexOf(".")+1;
postFileName = file.PostedFile.FileName.Substring(pos,file.PostedFile.FileName.Length-pos);
file.PostedFile.SaveAs(path+FileName+"."+postFileName); //儲存指定的檔案到指定的目錄
}
catch(Exception exec)
{
throw(exec);
}double unit = 1024;
double size = Math.Round(file.PostedFile.ContentLength/unit,2);
arr[(int)File.FILE_SIZE] = size.ToString(); //檔案大小
arr[(int)File.FILE_POSTNAME] = postFileName; //檔案類型(檔案尾碼名)
arr[(int)File.FILE_SYSNAME] = FileName; //檔案系統名
arr[(int)File.FILE_ORGINNAME] = FileOrginName; //檔案原來的名字
arr[(int)File.FILE_PATH]=path+FileName+"."+postFileName; //檔案路徑
return arr;
}public static bool OperateDB(string sqlstr) //建立一個和資料庫的關聯
{
if (sqlstr==String.Empty)
return false;SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connstring"]);
SqlCommand myCommand = new SqlCommand(sqlstr, myConnection);myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
return true;
}public static string GetUniquelyString() //擷取一個不重複的檔案名稱
{
const int RANDOM_MAX_VALUE = 1000;
string strTemp,strYear,strMonth,strDay,strHour,strMinute,strSecond,strMillisecond;DateTime dt =DateTime.Now;
int rndNumber = rnd.Next(RANDOM_MAX_VALUE);
strYear = dt.Year.ToString ();
strMonth = (dt.Month > 9)? dt.Month.ToString() : "0" + dt.Month.ToString();
strDay = (dt.Day > 9)? dt.Day.ToString() : "0" + dt.Day.ToString();
strHour = (dt.Hour > 9)? dt.Hour.ToString() : "0" + dt.Hour.ToString();
strMinute = (dt.Minute > 9)? dt.Minute.ToString() : "0" + dt.Minute.ToString();
strSecond = (dt.Second > 9)? dt.Second.ToString() : "0" + dt.Second.ToString();
strMillisecond = dt.Millisecond.ToString();strTemp = strYear + strMonth + strDay +"_"+ strHour + strMinute + strSecond +"_"+ strMillisecond +"_"+ rndNumber.ToString () ;return strTemp;
}
}
}
ASP.NET中檔案上傳下載方法集合檔案的上傳下載是我們在實際項目開發過程中經常需要用到的技術,這裡給出幾種常見的方法,本文主要內容包括: 1、如何解決檔案上傳大小的限制 2、以檔案形式儲存到伺服器 3、轉換成二進位位元組流儲存到資料庫以及下載方法 4、上傳Internet上的資源 第一部分: 首先我們來說一下如何解決ASP.net中的檔案上傳大小限制的問題,我們知道在預設情況下ASP.NET的檔案上傳大小限制為2M,一般情況下,我們可以採用更改Web.Config檔案來自訂最大檔案大小,如下: 這樣上傳檔案的最大值就變成了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()
{}
/**////
/// 上傳檔案名稱
///
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName; /**////
/// 上傳檔案路徑
///
public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath; /**////
/// 副檔名
///
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
</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
{
/**////
/// NetUFile 的摘要說明。
///
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上的資源到伺服器。 首先需要引用 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上讀取檔案,因此可以很好的解決這個問題。 第五部分:總結 今天簡單的介紹了幾種檔案上傳與下載的方法,都是在實際的項目開發中經常需要用到的,可能還有不完善的地方,希望大家可以互相交流一下項目開發中的經驗。