FCKeditor 上传修改,添加对文件的类型以及大小的限制(ASP.NET C#)

来源:互联网 发布:mac dreamweaver cs6 编辑:程序博客网 时间:2024/05/04 02:57

用了FCKeditor以后才知道,在性能上确实是挺优越的,特别是在加载的速度上,远比其它的编辑器要来得快,而且跨语言跨平台,也不会像FreeTextBox那样在页面中加入一大堆的ViewState视图状态代码,减轻了页面文件的重量,提高了加载速度. 

编辑器本身也内置了文件上传功能,但他却不对文件的类型以及大小做出限制,以至于带有安全忧患,万一给人上传了一个木马或者一个上面兆的影片文件怎么办,当然,修改*config.js文件可以解决,但似乎存在着某方面的安全隐患吧.

由于FCKeditor本身是开源的,所以我可以对里面的某些代码进行修改.

首先是对FileWorkerBase.cs基类的修改

using System;

namespace FredCK.FCKeditorV2
{
    
public abstract class FileWorkerBase : System.Web.UI.Page
    
{
        
private const string DEFAULT_USER_FILES_PATH = "/UserFiles/";

        
private const string DEFAULT_USER_FILES_UPLOADTYPE = ".jpg.jpeg.bmp.gif.png.zip.rar.swf.";//默认允许上传文件类型
        private const int DEFAULT_USER_FILES_UPLOADSIZE = 1024;//默认允许上传文件大小(1024KB)

        
private string sUserFilesPath;
        
private string sUserFilesDirectory;

        
private string sUserUploadType;
        
private int iUserUploadSize = 0;

        
protected string UserFilesPath
        
{
            
get
            
{
                
if (sUserFilesPath == null)
                
{
                    
// Try to get from the "Application".
                    sUserFilesPath = (string)Application["FCKeditor:UserFilesPath"];

                    
// Try to get from the "Session".
                    if (sUserFilesPath == null || sUserFilesPath.Length == 0)
                    
{
                        sUserFilesPath 
= (string)Session["FCKeditor:UserFilesPath"];

                        
// Try to get from the Web.config file.
                        if (sUserFilesPath == null || sUserFilesPath.Length == 0)
                        
{

                            sUserFilesPath 
= System.Web.Configuration.WebConfigurationManager.AppSettings["FCKeditor:UserFilesPath"];

                            
// Otherwise use the default value.
                            if (sUserFilesPath == null || sUserFilesPath.Length == 0)
                                sUserFilesPath 
= DEFAULT_USER_FILES_PATH;

                            
// Try to get from the URL.
                            if (sUserFilesPath == null || sUserFilesPath.Length == 0)
                            
{
                                sUserFilesPath 
= Request.QueryString["ServerPath"];
                            }

                        }

                    }


                    
// Check that the user path ends with slash ("/")
                    if (!sUserFilesPath.EndsWith("/"))
                        sUserFilesPath 
+= "/";
                }

                
return sUserFilesPath;
            }

        }



        
/// <summary>
        
/// The absolution path (server side) of the user files directory. It 
        
/// is based on the <see cref="FileWorkerBase.UserFilesPath"/>.
        
/// </summary>

        protected string UserFilesDirectory
        
{
            
get
            
{
                
if (sUserFilesDirectory == null)
                
{
                    
// Get the local (server) directory path translation.
                    sUserFilesDirectory = Server.MapPath(this.UserFilesPath);
                }

                
return sUserFilesDirectory;
            }

        }


        
/// <summary>
        
/// 获取允许上传的类型
        
/// </summary>

        protected string UserUploadType
        
{
            
get
            
{
                
if (sUserUploadType == null)
                
{
                    
// Try to get from the "Application".
                    sUserUploadType = (string)Application["FCKeditor:UserUploadType"];

                    
// Try to get from the "Session".
                    if (sUserUploadType == null || sUserUploadType.Length == 0)
                    
{
                        sUserUploadType 
= (string)Session["FCKeditor:UserUploadType"];

                        
// Try to get from the Web.config file.
                        if (sUserUploadType == null || sUserUploadType.Length == 0)
                        
{

                            sUserUploadType 
= System.Web.Configuration.WebConfigurationManager.AppSettings["FCKeditor:UserUploadType"];

                            
// Otherwise use the default value.
                            if (sUserUploadType == null || sUserUploadType.Length == 0)
                                sUserUploadType 
= DEFAULT_USER_FILES_UPLOADTYPE;

                        }

                    }


                    
// Check that the user path starts and ends with slash (".")
                    if (!sUserUploadType.StartsWith("."))
                        sUserUploadType 
= "." + sUserUploadType;

                    
if (!sUserUploadType.EndsWith("."))
                        sUserUploadType 
+= ".";
                }

                
return sUserUploadType;
            }

        }


        
/// <summary>
        
/// 获取允许上传的文件最大限制
        
/// </summary>

        protected int UserUploadSize
        
{
            
get
            
{
                
if (iUserUploadSize < 1)
                
{
                    iUserUploadSize 
= Convert.ToInt32(Application["FCKeditor:UserUploadSize"]);
                    
if (iUserUploadSize < 1)
                    
{
                        iUserUploadSize 
= Convert.ToInt32(Session["FCKeditor:UserUploadSize"]);
                        
if (iUserUploadSize < 1)
                        
{
                            iUserUploadSize 
= Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["FCKeditor:UserUploadSize"]);
                            
if (iUserUploadSize < 1)
                            
{
                                iUserUploadSize 
= DEFAULT_USER_FILES_UPLOADSIZE;
                            }

                        }

                    }

                }


                
return iUserUploadSize;
            }

        }

    }

}

接着就是对点击"浏览服务器"页面的上传部分的修改

以下是对FileBrowserConnector.cs中的FileUpload()函数的修改

  private void FileUpload(string resourceType, string currentFolder)
        
{
            HttpPostedFile oFile 
= Request.Files["NewFile"];

            
string sErrorNumber = "0";
            
string sFileName = "";

            
if (oFile != null && oFile.ContentLength > 0)
            
{
                
// Map the virtual path to the local server path.
                string sServerDir = this.ServerMapFolder(resourceType, currentFolder);
                
/*
                // Get the uploaded file name.
                sFileName = System.IO.Path.GetFileName( oFile.FileName ) ;

                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 ;
                    }
                }
                
*/

                
if (this.UserUploadType.ToLower().IndexOf(System.IO.Path.GetExtension(oFile.FileName).ToLower() + "."> -1)//检测是否为允许的上传文件类型
                {
                    
if (this.UserUploadSize * 1024 >= oFile.ContentLength)//检测文件大小是否超过限制
                    {
                        sFileName 
= DateTime.Now.ToString("yyyyMMddHHmmssffff"+ System.IO.Path.GetExtension(oFile.FileName);
                        
string sFilePath = System.IO.Path.Combine(sServerDir, sFileName);
                        oFile.SaveAs(sFilePath);
                    }

                    
else//文件大小超过限制
                    {
                        Response.Clear();

                        Response.Write(
"<script type="text/javascript">");
                        Response.Write(
"window.parent.frames['frmUpload'].OnUploadCompleted(1,'上传文件大小超出限制') ;");
                        Response.Write(
"</script>");

                        Response.End();
                    }

                }

                
else //文件类型不允许上传
                {
                    Response.Clear();

                    Response.Write(
"<script type="text/javascript">");
                    Response.Write(
"window.parent.frames['frmUpload'].OnUploadCompleted(1,'上传文件类型不允许') ;");
                    Response.Write(
"</script>");

                    Response.End();
                }




            }

            
else
                sErrorNumber 
= "202";

            Response.Clear();

            Response.Write(
"<script type="text/javascript">");
            Response.Write(
"window.parent.frames['frmUpload'].OnUploadCompleted(" + sErrorNumber + ",'" + sFileName.Replace("'""/'"+ "') ;");
            Response.Write(
"</script>");

            Response.End();
        }

最后就是对Uploader.cs类中的OnLoad()函数的修改

 protected override void OnLoad(EventArgs e)
        
{
            
// Get the posted file.
            HttpPostedFile oFile = Request.Files["NewFile"];

            
// Check if the file has been correctly uploaded
            if (oFile == null || oFile.ContentLength == 0)
            
{
                SendResults(
202);
                
return;
            }


            
int iErrorNumber = 0;
            
string sFileUrl = "";
            
string sFileName = "";
            
//使用原文件名上传代码,如果文件名相同,则在后面加上标号(1)(2)...
            /*
            // Get the uploaded file name.
            string sFileName = System.IO.Path.GetFileName( oFile.FileName ) ;

            
            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 ;
                }
            }
             
*/

            
//使用原文件名上传代码结束
            
//使用时间作为流水号文件名


            
if (this.UserUploadSize * 1024 >= oFile.ContentLength)//检测文件大小是否超过限制
            {
                sFileName 
= DateTime.Now.ToString("yyyyMMddHHmmssffff"+ System.IO.Path.GetExtension(oFile.FileName);
                
string sFilePath = System.IO.Path.Combine(this.UserFilesDirectory, sFileName);
                oFile.SaveAs(sFilePath);

                sFileUrl 
= this.UserFilesPath + sFileName;
            }

            
else//文件大小超过限制
            {
                SendResults(
1"""""上传文件大小超出限制");

            }


            
/////////////////////////////////////////////////////////////////////////////

            SendResults(iErrorNumber, sFileUrl, sFileName);
        }

最后只要在Web.Config文件中加入对文件上传的限制值就可以了.

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>  
<add key="FCKeditor:UserFilesPath" value="/UserFiles/" />
<add key="FCKeditor:UserUploadType" value=".gif.jpg.jpeg.rar.zip.swf.png" />
<add key="FCKeditor:UserUploadSize" value="5120" /><!--单位为KB-->  
 
</appSettings>
 
<system.web>
     
<httpRuntime maxRequestLength="512000" />  
  
</system.web>

 
</configuration>

 

 

 

原创粉丝点击