Asp.net上傳文件至目錄

//上傳時,判斷文件是否大於限定大小
        if (this.FileUpload1.PostedFile.ContentLength > 104857600//單位KB
        {
            objInsusJsUtility.JsAlert(
"You select the file larger than 100MB");
            
return;
        }

        
//創建一個臨時文件夾
        string tempPath = "~/Temp/";
        
//判斷目錄是否存在
        if (!Directory.Exists(Server.MapPath(tempPath)))
        {
            
//如果不存在,創建它
            Directory.CreateDirectory(Server.MapPath(tempPath));
        }

       
//取得上傳文件
        string uploadfile = FileUpload1.PostedFile.FileName;
        
//取得原文件名,存入數據庫中,這樣在aspx顯示回原來的文件名
        string oldFileName = uploadfile.Substring(uploadfile.LastIndexOf(@"/"+ 1);
        
//取得文件的擴展名
        string fileExtension = uploadfile.Substring(uploadfile.LastIndexOf("."));
        
//產生新文件名
        string newFileName = objGuid.ToString() + fileExtension;

        
//建立存儲的目錄
        string directory = Mediadirectory + this.ddlMediaType.SelectedItem.Value + "/";
        
        
//判斷目錄是否存在
        if (!Directory.Exists(Server.MapPath(directory)))
        {
           
//如果不存在,創建它
            Directory.CreateDirectory(Server.MapPath(directory));
        }

        
//新文件
        string newFile = Server.MapPath(tempPath + newFileName);
        
        
//保存文件(暫存入一個臨時文件夾中)
        FileUpload1.SaveAs(newFile);

        
//限定上傳的文件類型
        string[] fileClass = { "7076""4838" };  //7076 is FLV;4838 is wmv;
        if (!InsusBase.CompareFileClass(newFile, fileClass))
        {
            objInsusJsUtility.JsAlert(
"You did not specify a media file.The file format is wmv,flv");
            
return;
        }

        
try
        {
           
//存入數據庫中
            objMedia.Insert(this.ddlMediaType.SelectedItem.Value, this.txtSubject.Text.Trim(), this.txtDescription.Text.Trim(), directory, oldFileName, newFileName);
            
//把文件從臨時文件夾中,移至真正的目錄。
            File.Move(newFile, Server.MapPath(directory + newFileName));
            objInsusJsUtility.JsAlert(
"視頻上傳成功。""this""Media.aspx");
        }
        
catch (Exception ex)
        {
            
//拋出異常
            InsusBase.InsusException(ex);
        }

Web.config配置可上傳大文件,asp.net默認情況之下只能上傳4MB,另外一點就是,maxRequestLength單位是MB。

<system.web>      
        
<httpRuntime maxRequestLength="102400" useFullyQualifiedRedirectUrl="true" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/>
    
</system.web>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章