FCKeditor V2.x上传文件自动重命名

来源:互联网 发布:linux etc profile 编辑:程序博客网 时间:2024/05/19 18:13
转自www1.biochems.cn

  FCKeditor 的文件上传默认是不改名的,本地的文件名是什么,上传后保留原来的文件名;如果存在同名文件,则会被自动在文件名后面加 (n) 来标识。但是如果原文件名中包含有空格或标点,则有可能会出现能上传但不能引用的情况。我们可以通过修改,让 FCKeditor 自动生成不重复且不含非法字符的文件名,思路是根据精确到秒的上传时间来命名,然后存放在服务器上。
  For ASP.NET 的修改相对其他语言较麻烦一些,上传部分都编译到 DLL 文件里面了,只能通过修改源代码,再重新编译后方能使用。上传其实分2部分,一是“快速上传”,即在网页对话框中点“上传”标签后出来的界面,通过这里上传的文件都会存放在 UserFiles 根目录,如下图:

还有一个上传在点击“浏览服务器”后出来的界面中,我称之为“选择性上传”,这部分上传的文件则会根据用户选择的不同资源存放在相应的目录,或是 Image 或是 Flash、File等等。
  用 VS.NET 打开 FredCK.FCKeditorV2.csproj,打开 Uploader.cs 文件,通过文件开头的注释:This is the code behind of the uploader.aspx page used for Quick Uploads.可以得知该文件是控制“快速上传”的,找到以下代码:   

int iCounter = 0 ;
   
while ( true )
   
{
    
string sFilePath = System.IO.Path.Combine( this.UserFilesDirectory, sFileName ) ;

    
if ( System.IO.File.Exists( sFilePath ) )
    
{
     iCounter
++ ;
     sFileName 
= 
      System.IO.Path.GetFileNameWithoutExtension( oFile.FileName ) 
+
      
"(" + iCounter + ")" +
      System.IO.Path.GetExtension( oFile.FileName ) ;

     iErrorNumber 
= 201 ;
    }

    
else
    
{
     oFile.SaveAs( sFilePath ) ;

     sFileUrl 
= this.UserFilesPath + sFileName ;
     
break ;
    }

   }

 

大意是如果存在同名文件则在文件名后加入 (n) 来标识,否则以原文件名保存。把它改成不论有没有同名文件,都重新生成一个新的文件名。修改后的代码变成:   

while ( true )
   
{
    
// Rebuild file name.
    sFileName = DateTime.Now.ToString().Replace("-","").Replace(" ","").Replace(":","")+System.IO.Path.GetExtension(oFile.FileName);
    
string sFilePath = System.IO.Path.Combine( this.UserFilesDirectory, sFileName ) ;

    oFile.SaveAs( sFilePath ) ;
    sFileUrl 
= this.UserFilesPath + sFileName ;
    
break ;
   }

 

DataTime.Now.ToString()是获取当前时间并转换为字符串,得到的结果以 YYYY-MM-DD HH:MM:SS 的形式出现,用 Replace 把其中的分隔符及空格替换掉;再加上原文件的扩展名,“快速上传”修改完成。上传后的文件以 2005126152012.jpg 的命名方式存放到服务器上。
  再打开 FileBrowserConnector.cs 文件,找到 Command Handlers 区中的 FileUpload 函数段,同样是修改 while 语句中的内容:      

int iCounter = 0 ;

    
while ( true )
    
{
     
string sFilePath = System.IO.Path.Combine( sServerDir, sFileName ) ;

     
if ( System.IO.File.Exists( sFilePath ) )
     
{
      iCounter
++ ;
      sFileName 
= 
       System.IO.Path.GetFileNameWithoutExtension( oFile.FileName ) 
+
       
"(" + iCounter + ")" +
       System.IO.Path.GetExtension( oFile.FileName ) ;

      sErrorNumber 
= "201" ;
     }

     
else
     
{
      oFile.SaveAs( sFilePath ) ;
      
break ;
     }

    }

 

把它改成:    

while ( true )
    
{
     
// Rebuild file name.
     sFileName = DateTime.Now.ToString().Replace("-","").Replace(" ","").Replace(":","")+System.IO.Path.GetExtension(oFile.FileName);
     
string sFilePath = System.IO.Path.Combine( sServerDir, sFileName ) ;
     oFile.SaveAs( sFilePath ) ;
     
break ;
    }

 

因为不再使用 iCounter 变量,所以一并去除。保存文件,重新生成解决方案;打开网站项目,在引用中删除原来的 FredCK.FCKeditorV2,再把刚才生成的 FredCK.FCKeditorV2.dll 文件复制到网站 bin 目录下,重新添加引用、生成,就大功告成了。
  文件的命名方式只是个人喜好,也许有人觉得如此只有数字串的名称反而更不直观;重新编译生成的 FredCK.FCKeditorV2.dll 就不提供了……

原创粉丝点击