簡單檔案的上傳與儲存

iDotNetSpace發表於2008-09-23
本文簡單地使用Asp.net中FileUpload元件實現簡單的檔案的上傳

頁面前臺部分

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt<asp:FileUpload ID="myFile" runat="server" BorderColor="Silver"   BorderStyle="Solid" BorderWidth="1px" />

附件實體類

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt    /// 
    
/// 附件,加一個實體化類是為了用orm的方式儲存附件物件,屬性根據自己需要新增
    
/// 
    public class Attachment
    {
        
public int Id { getset; }

        
public string Name { getset; }

        
public string ExtendName { getset; }

        
public long Size { getset; }

        
public int IsUsed { getset; }

        
public string Descript { getset; }

        
public byte[] Content { getset; }
     }

 

頁面後臺程式碼,頁面上傳按鈕的單擊事件中新增程式碼,呼叫如下函式

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtvoid saveToDataBase()
{
    
string fileName = myFile.FileName;
    
string fileType = myFile.PostedFile.ContentType;
    
long size = myFile.FileContent.Length;
    
string descript = myDescript.Text;
    
//new一個實體物件
    Attachment attachmentObj = new Attachment();
    attachmentObj.Id 
= 0;
    attachmentObj.Name 
= fileName;
    attachmentObj.ExtendName 
= fileType;
    attachmentObj.Size 
= size;
    attachmentObj.Descript 
= descript;
    attachmentObj.Content 
= myFile.FileBytes;

    
//orm方式儲存附件物件,如NHibernate等             
     save(attachmentObj);

    
//其他處理程式碼,或註冊客戶端指令碼事件或語句
}

 

後面的話:

當然如果想做得比較完美的話,
1)首先在客戶端可以新增一些驗證,什麼檔案允許新增,伺服器端也要有一些驗證。
2)多個檔案同時上傳等
3)Ajax進度條等

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-462650/,如需轉載,請註明出處,否則將追究法律責任。

相關文章