1. 程式人生 > >ASP環境,百度Ueditor 無法上傳附件,提示405錯誤或者404錯誤解決辦法。

ASP環境,百度Ueditor 無法上傳附件,提示405錯誤或者404錯誤解決辦法。

UEditor是由百度web前端研發部開發所見即所得富文字web編輯器,具有輕量,可定製,注重使用者體驗等特點,開源基於BSD協議,允許自由使用和修改程式碼...

在Ueditor1.2.0.0和之前的版本都支援asp,但是附件上傳是無法使用的,通過檢視程式碼後發現,Ueditor根本就沒有提供asp環境下的附件上傳功能,百度這麼大的公司也有不厚道的時候,難道Ueditor開發組是為了從安全形度考慮而放棄了這個功能?不管什麼原因,只好自己弄一個,解決辦法如下:

1、找到Ueditor所在目錄下的dialogs\attachment\attachment.html,開啟後找到裡面的

upload_url:"../../server/upload/php/fileUp.php"

改為:

upload_url:"../../server/upload/asp/FileUp.asp"

附上attachment.html檔案,如果你找不到attachment.html檔案,那就Copy一下吧,內容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>附件上傳</title>
    <meta http-equiv="Content-Type" content="text/html;charset=gbk"/>
    <link rel="stylesheet" type="text/css" href="attachment.css"/>
</head>
<body>
<div class="wrapper">
    <div class="controller">
        <span id="divStatus">本次共成功上傳 0 個檔案</span>
        <span id="spanButtonPlaceHolder"></span>
    </div>
    <div class="fieldset flash" id="fsUploadProgress"></div>
    <span id="startUpload" style="display: none;"></span>

</div>
<script type="text/javascript" src="../internal.js"></script>

<script type="text/javascript" src="../../third-party/swfupload/swfupload.js"></script>
<script type="text/javascript" src="../../third-party/swfupload/swfupload.queue.js"></script>
<script type="text/javascript" src="../../third-party/swfupload/fileprogress.js"></script>
<script type="text/javascript" src="callbacks.js"></script>
<script type="text/javascript" src="fileTypeMaps.js"></script>
<script type="text/javascript">
    var swfupload,
        filesList=[];
    window.onload = function () {
        var settings = {
            flash_url:"../../third-party/swfupload/swfupload.swf",
            flash9_url:"../../third-party/swfupload/swfupload_fp9.swf",
            upload_url:"../../server/upload/asp/FileUp.asp",           //附件上傳伺服器地址
            post_params:{"PHPSESSID":"<?php echo session_id(); ?>"}, //解決session丟失問題
            file_size_limit:"100 MB",                                 //檔案大小限制,此處僅是前端flash選擇時候的限制,具體還需要和後端結合判斷
            file_types:"*.*",                                         //允許的副檔名,多個副檔名之間用分號隔開,支援*萬用字元
            file_types_description:"All Files",                      //副檔名描述
            file_upload_limit:100,                                   //單次可同時上傳的檔案數目
            file_queue_limit:10,                                      //佇列中可同時上傳的檔案數目
            custom_settings:{                                         //自定義設定,使用者可在此向伺服器傳遞自定義變數
                progressTarget:"fsUploadProgress",
                startUploadId:"startUpload"
            },
            debug:false,

            // 按鈕設定
            button_image_url:"../../themes/default/images/fileScan.png",
            button_width:"100",
            button_height:"25",
            button_placeholder_id:"spanButtonPlaceHolder",
            button_text:'<span class="theFont">檔案瀏覽…</span>',
            button_text_style:".theFont { font-size:14px;}",
            button_text_left_padding:10,
            button_text_top_padding:4,

            // 所有回撥函式 in handlers.js
            swfupload_preload_handler:preLoad,
            swfupload_load_failed_handler:loadFailed,
            file_queued_handler:fileQueued,
            file_queue_error_handler:fileQueueError,
            //選擇檔案完成回撥
            file_dialog_complete_handler:function(numFilesSelected, numFilesQueued) {
                var me = this;        //此處的this是swfupload物件
                if (numFilesQueued > 0) {
                    dialog.buttons[0].setDisabled(true);
                    var start = $G(this.customSettings.startUploadId);
                    start.style.display = "";
                    start.onclick = function(){
                        me.startUpload();
                        start.style.display = "none";
                    }
                }
            },
            upload_start_handler:uploadStart,
            upload_progress_handler:uploadProgress,
            upload_error_handler:uploadError,
            upload_success_handler:function (file, serverData) {
                try{
                    var info = eval("("+serverData+")");
                }catch(e){}
                var progress = new FileProgress(file, this.customSettings.progressTarget);
                if(info.state=="SUCCESS"){
                    progress.setComplete();
                    progress.setStatus("<span style='color: #0b0;font-weight: bold'>上傳成功!</span>");
                    filesList.push({url:info.url,type:info.fileType});
                    progress.toggleCancel(true,this,"從成功佇列中移除");
                }else{
                    progress.setError();
                    progress.setStatus(info.state);
                    progress.toggleCancel(true,this,"移除儲存失敗檔案");
                }

            },
            //上傳完成回撥
            upload_complete_handler:uploadComplete,
            //佇列完成回撥
            queue_complete_handler:function(numFilesUploaded){
                dialog.buttons[0].setDisabled(false);
                var status = $G("divStatus");
                var num = status.innerHTML.match(/\d+/g);
                status.innerHTML = "本次共成功上傳 "+((num && num[0] ?parseInt(num[0]):0) + numFilesUploaded) +" 個檔案" ;
            }
        };
        swfupload = new SWFUpload( settings );
        //點選OK按鈕
        dialog.onok = function(){
            var map = fileTypeMaps,
                str="";
            for(var i=0,ci;ci=filesList[i++];){
                var src = editor.options.UEDITOR_HOME_URL + "dialogs/attachment/fileTypeImages/"+(map[ci.type]||"icon_default.png");
                str += "<p style='line-height: 16px;'><img src='"+ src + "' data_ue_src='"+src+"' />" +
                       "<a href='"+editor.options.filePath + ci.url+"'>" + ci.url + "</a></p>";
            }
            editor.execCommand("insertHTML",str);
            swfupload.destroy();
        };
        dialog.oncancel = function(){
            swfupload.destroy();
        }
    };
</script>

</body>
</html>

2、在Ueditor所在目錄下的server/upload/asp新建一個檔案FileUp.asp,內容如下:

<!--#include file="upload.inc"-->
<%dim upload,file,formName,formPath,filename,fileExt
dim maxSize
maxSize = 5000000	'允許上傳的檔案最大容量

set upload=new upload_5xSoft ''建立上傳物件
formPath="/uploadFile/" '檔案上傳存放路徑,這個目錄在你網站上必須存在,否則會出錯。

for each formName in upload.file ''列出所有上傳了的檔案
	set file=upload.file(formName)  ''生成一個檔案物件

	fileExt=lcase(right(file.filename,4))

	'定義可上傳的檔案型別
	If fileEXT<>".doc" and fileEXT<>".txt" and fileEXT<>".zip" and fileEXT<>".rar" and fileEXT<>".pdf" and fileEXT<>".xls" then
 		response.write "{'state':'ERROR!檔案型別錯誤!','url':'"&file.filename&"','fileType':'"&fileExT&"'}"
		response.end
	End If 
 
	randomize
	ranNum=int(90000*rnd)+10000
	filename=formPath&year(now)&month(now)&day(now)&ranNum&fileExt   '檔名稱
 
	If file.FileSize>0 or file.filesize<maxSize then
		file.SaveAs Server.mappath(FileName)   '儲存檔案
	Else
		response.write "{'state':'ERROR!檔案容量限制!','url':'"&file.filename&"','fileType':'"&fileExT&"'}"
		response.end
	End If
	set file=nothing
next
set upload=nothing  ''刪除此物件%>
{'state':'SUCCESS','url':'<%=filename%>','fileType':'<%=fileEXT%>'}

3、如果Ueditor所在目錄下的server/upload/asp目錄下沒有upload.inc檔案,那麼你要手工建一個,附上upload.inc檔案內容

<SCRIPT RUNAT=SERVER LANGUAGE=VBSCRIPT>
    dim upfile_5xSoft_Stream

    Class upload_5xSoft

    dim Form,File,Version

    Private Sub Class_Initialize
    dim iStart,iFileNameStart,iFileNameEnd,iEnd,vbEnter,iFormStart,iFormEnd,theFile
    dim strDiv,mFormName,mFormValue,mFileName,mFileSize,mFilePath,iDivLen,mStr
    Version=""
    if Request.TotalBytes<1 then Exit Sub
    set Form=CreateObject("Scripting.Dictionary")
    set File=CreateObject("Scripting.Dictionary")
    set upfile_5xSoft_Stream=CreateObject("Adodb.Stream")
    upfile_5xSoft_Stream.mode=3
    upfile_5xSoft_Stream.type=1
    upfile_5xSoft_Stream.open
    upfile_5xSoft_Stream.write Request.BinaryRead(Request.TotalBytes)

    vbEnter=Chr(13)&Chr(10)
    iDivLen=inString(1,vbEnter)+1
    strDiv=subString(1,iDivLen)
    iFormStart=iDivLen
    iFormEnd=inString(iformStart,strDiv)-1
    while iFormStart < iFormEnd
    iStart=inString(iFormStart,"name=""")
    iEnd=inString(iStart+6,"""")
    mFormName=subString(iStart+6,iEnd-iStart-6)
    iFileNameStart=inString(iEnd+1,"filename=""")
    if iFileNameStart>0 and iFileNameStart<iFormEnd then
    iFileNameEnd=inString(iFileNameStart+10,"""")
    mFileName=subString(iFileNameStart+10,iFileNameEnd-iFileNameStart-10)
    iStart=inString(iFileNameEnd+1,vbEnter&vbEnter)
    iEnd=inString(iStart+4,vbEnter&strDiv)
    if iEnd>iStart then
    mFileSize=iEnd-iStart-4
    else
    mFileSize=0
    end if
    set theFile=new FileInfo
    theFile.FileName=getFileName(mFileName)
    theFile.FilePath=getFilePath(mFileName)
    theFile.FileSize=mFileSize
    theFile.FileStart=iStart+4
    theFile.FormName=FormName
    file.add mFormName,theFile
    else
    iStart=inString(iEnd+1,vbEnter&vbEnter)
    iEnd=inString(iStart+4,vbEnter&strDiv)

    if iEnd>iStart then
    mFormValue=subString(iStart+4,iEnd-iStart-4)
    else
    mFormValue=""
    end if
    form.Add mFormName,mFormValue
    end if

    iFormStart=iformEnd+iDivLen
    iFormEnd=inString(iformStart,strDiv)-1
    wend
    End Sub

    Private Function subString(theStart,theLen)
    dim i,c,stemp
    upfile_5xSoft_Stream.Position=theStart-1
    stemp=""
    for i=1 to theLen
    if upfile_5xSoft_Stream.EOS then Exit for
    c=ascB(upfile_5xSoft_Stream.Read(1))
    If c > 127 Then
    if upfile_5xSoft_Stream.EOS then Exit for
    stemp=stemp&Chr(AscW(ChrB(AscB(upfile_5xSoft_Stream.Read(1)))&ChrB(c)))
    i=i+1
    else
    stemp=stemp&Chr(c)
    End If
    Next
    subString=stemp
    End function

    Private Function inString(theStart,varStr)
    dim i,j,bt,theLen,str
    InString=0
    Str=toByte(varStr)
    theLen=LenB(Str)
    for i=theStart to upfile_5xSoft_Stream.Size-theLen
    if i>upfile_5xSoft_Stream.size then exit Function
    upfile_5xSoft_Stream.Position=i-1
    if AscB(upfile_5xSoft_Stream.Read(1))=AscB(midB(Str,1)) then
    InString=i
    for j=2 to theLen
    if upfile_5xSoft_Stream.EOS then
    inString=0
    Exit for
    end if
    if AscB(upfile_5xSoft_Stream.Read(1))<>AscB(MidB(Str,j,1)) then
    InString=0
    Exit For
    end if
    next
    if InString<>0 then Exit Function
    end if
    next
    End Function

    Private Sub Class_Terminate
    form.RemoveAll
    file.RemoveAll
    set form=nothing
    set file=nothing
    upfile_5xSoft_Stream.close
    set upfile_5xSoft_Stream=nothing
    End Sub


    Private function GetFilePath(FullPath)
    If FullPath <> "" Then
    GetFilePath = left(FullPath,InStrRev(FullPath, "\"))
    Else
    GetFilePath = ""
    End If
    End function

    Private function GetFileName(FullPath)
    If FullPath <> "" Then
    GetFileName = mid(FullPath,InStrRev(FullPath, "\")+1)
    Else
    GetFileName = ""
    End If
    End function

    Private function toByte(Str)
    dim i,iCode,c,iLow,iHigh
    toByte=""
    For i=1 To Len(Str)
    c=mid(Str,i,1)
    iCode =Asc(c)
    If iCode<0 Then iCode = iCode + 65535
    If iCode>255 Then
    iLow = Left(Hex(Asc(c)),2)
    iHigh =Right(Hex(Asc(c)),2)
    toByte = toByte & chrB("&H"&iLow) & chrB("&H"&iHigh)
    Else
    toByte = toByte & chrB(AscB(c))
    End If
    Next
    End function
    End Class


    Class FileInfo
    dim FormName,FileName,FilePath,FileSize,FileStart
    Private Sub Class_Initialize
    FileName = ""
    FilePath = ""
    FileSize = 0
    FileStart= 0
    FormName = ""
    End Sub

    Public function SaveAs(FullPath)
    dim dr,ErrorChar,i
    SaveAs=1
    if trim(fullpath)="" or FileSize=0 or FileStart=0 or FileName="" then exit function
    if FileStart=0 or right(fullpath,1)="/" then exit function
    set dr=CreateObject("Adodb.Stream")
    dr.Mode=3
    dr.Type=1
    dr.Open
    upfile_5xSoft_Stream.position=FileStart-1
    upfile_5xSoft_Stream.copyto dr,FileSize
    dr.SaveToFile FullPath,2
    dr.Close
    set dr=nothing
    SaveAs=0
    end function
    End Class 
</SCRIPT>


4、關於安全問題補充:由於FileUp.asp未加入許可權驗證,所以是不安全的,因此建議在FileUp.asp檔案裡面要加入許可權驗證,例如用session驗證。

以上解決辦法在Ueditor1.2.0.0版本上驗證成功!同時附件下載地址:
2012-03-29 [1.2.0.0 版本] UTF-8版 GBK版