Asp.net上传文件至目录

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 >

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值