RemoteUpload Plugin for FCKEditor 2.6 java 版(2.4)

啥也不说了,亮代码。

RemoteUploadServlet.java 远程文件url处理。

package com.ccr.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.fckeditor.connector.Messages;
import net.fckeditor.handlers.ConnectorHandler;
import net.fckeditor.handlers.ExtensionsHandler;
import net.fckeditor.handlers.RequestCycleHandler;
import net.fckeditor.handlers.ResourceTypeHandler;
import net.fckeditor.response.UploadResponse;
import net.fckeditor.tool.Utils;
import net.fckeditor.tool.UtilsFile;
import net.fckeditor.tool.UtilsResponse;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ccr.tools.RemoteFile;

public class RemoteUploadServlet extends HttpServlet {

	private static final long serialVersionUID = -648261400947668425L;
	private static final Logger logger = LoggerFactory
			.getLogger(RemoteUploadServlet.class);

	/**
	 * Initialize the servlet.<br>
	 * The default directory for user files will be constructed.
	 */
	public void init() throws ServletException, IllegalArgumentException {
		// check, if 'baseDir' exists
		String realDefaultUserFilesPath = getServletContext().getRealPath(
				ConnectorHandler.getDefaultUserFilesPath());

		File defaultUserFilesDir = new File(realDefaultUserFilesPath);
		UtilsFile.checkDirAndCreate(defaultUserFilesDir);

		logger.info("RemoteUploadServlet successful initialized!");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug("Entering RemoteUploadServlet#doGet");

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/xml; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();

		String commandStr = request.getParameter("Command");
		String typeStr = request.getParameter("Type");
		String currentFolderStr = request.getParameter("CurrentFolder");

		logger.debug("Parameter Command: {}", commandStr);
		logger.debug("Parameter Type: {}", typeStr);
		logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

		out.print("");
		out.flush();
		out.close();
		logger.debug("Exiting ConnectorServlet#doGet");
	}
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	        throws ServletException, IOException {
		logger.debug("Entering RemoteUploadServlet#doPost");

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		String commandStr = request.getParameter("Command");
		String typeStr = request.getParameter("Type");
		String currentFolderStr = request.getParameter("CurrentFolder");

		logger.debug("Parameter Command: {}", commandStr);
		logger.debug("Parameter Type: {}", typeStr);
		logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

		UploadResponse ur;

		// if this is a QuickUpload-Request, 'commandStr' and 'currentFolderStr' are empty
		if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
			commandStr = "Remote";
			currentFolderStr = "/";
		}
		
		if (!RequestCycleHandler.isEnabledForFileUpload(request))
			ur = new UploadResponse(UploadResponse.EN_SECURITY_ERROR, null, null,
			        Messages.NOT_AUTHORIZED_FOR_UPLOAD);
		else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
			ur = new UploadResponse(UploadResponse.EN_ERROR, null, null, Messages.INVALID_TYPE);
		else if (!UtilsFile.isValidPath(currentFolderStr))
			ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
		else {
			ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

			String typePath = UtilsResponse.constructResponseUrl(request, resourceType,
			        currentFolderStr, false, false);
			String typeDirPath = getServletContext().getRealPath(typePath);

			File typeDir = new File(typeDirPath);
			UtilsFile.checkDirAndCreate(typeDir);

			File currentDir = new File(typeDir, currentFolderStr);

			if (!currentDir.exists())
				ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
			else {

				String saveFilenames = "";
				String pathFilename = "";
				String contentString;
				String remoteFileurl = null;
				String newFilename = null;
				int nFileNum = 0;
				contentString = request.getParameter("editor_UploadText");
				if (!Utils.isEmpty(contentString)) {
					Pattern pRemoteFileurl = Pattern
							.compile("((http|https|ftp|rtsp|mms):(//|\\\\){1}(([A-Za-z0-9_-])+[.]){1,}(net|com|cn|org|cc|tv|[0-9]{1,3})(\\S*/)((\\S)+[.]{1}([^'\" ])+))");
					Matcher mRemoteFileurl = pRemoteFileurl.matcher(contentString);
					StringBuffer sb = new StringBuffer();
					while (mRemoteFileurl.find()) {
						remoteFileurl = mRemoteFileurl.group(0);
						String remoteFilename =remoteFileurl.substring(remoteFileurl.lastIndexOf("/") + 1);
						String rawName = UtilsFile.sanitizeFileName(remoteFilename);
						String filename = FilenameUtils.getName(rawName);
						String baseName = FilenameUtils.removeExtension(filename);
						String extension = FilenameUtils.getExtension(filename);
						if (ExtensionsHandler.isAllowed(resourceType, extension)) {
							String fileUrl = "";
							// construct an unique file name
							File pathToSave = new File(currentDir, filename);
							int counter = 1;
							while (pathToSave.exists()) {
								newFilename = baseName.concat("(").concat(String.valueOf(counter))
								        .concat(")").concat(".").concat(extension);
								pathToSave = new File(currentDir, newFilename);
								counter++;
							}
							if (Utils.isEmpty(newFilename)) {
								fileUrl = UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
								                true, ConnectorHandler.isFullUrl()).concat(filename);
								newFilename = filename;
							}
							else {
								fileUrl = UtilsResponse.constructResponseUrl(request, resourceType,
								                currentFolderStr, true, ConnectorHandler.isFullUrl())
								                .concat(newFilename);
							}
							if (RemoteFile.saveUrlAs(remoteFileurl, pathToSave.getAbsolutePath())) {
								nFileNum ++;
								if (nFileNum > 1) {
									saveFilenames += "|";
									pathFilename += "|";
								}
								saveFilenames += newFilename;
								pathFilename += fileUrl;
								mRemoteFileurl.appendReplacement(sb,
										fileUrl);
							}
						}
					}
					mRemoteFileurl.appendTail(sb);
					contentString = sb.toString();
					contentString=inHTML(contentString);
				}
				ur = new UploadResponse(UploadResponse.EN_OK, pathFilename, saveFilenames, contentString.replaceAll("'", "{\"}"));
			}

		}
		out.print(ur);
		out.flush();
		out.close();

		logger.debug("Exiting Connector#doPost");
	}

	 private String inHTML(String str)
	 {
	 	String sTemp;
	 	sTemp = str;
	 	if(sTemp.equals(""))
	 	{
	 		System.exit(0);
	 	}
	 	sTemp = sTemp.replaceAll("&", "&");
	 	sTemp = sTemp.replaceAll("<", "<");
	 	sTemp = sTemp.replaceAll(">", ">");
	 	return sTemp;
	 }

}

 

 

RemoteFile.java 远程文件保存

package com.ccr.tools;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class RemoteFile {
	public static boolean saveUrlAs(String fileUrl, String savePath) {
		try {
			URL url = new URL(fileUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			DataInputStream in = new DataInputStream(connection
					.getInputStream());
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					savePath));
			byte[] buffer = new byte[4096];
			int count = 0;
			while ((count = in.read(buffer)) > 0) {
				out.write(buffer, 0, count);
			}
			out.close();
			in.close();
			connection.disconnect();
			return true;

		} catch (Exception e) {
			System.out.println(e + fileUrl + savePath);
			return false;
		}
	}

	/**
	 * 兼容HTTP和FTP协议
	 * @param urlString
	 * @return
	 */
	public static String getDocumentAt(String urlString) {
		StringBuffer document = new StringBuffer();

		try {

			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				document.append(line + "\n");
			}
			reader.close();
		} catch (MalformedURLException e) {
			System.out.println("Unable to connect to URL: " + urlString);
		} catch (IOException e) {
			System.out.println("IOException when connecting to URL: "
					+ urlString);
		}
		return document.toString();
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String photoUrl = "http://www.zhplc.com/468x60.gif";
		String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
		String filePath = "c:\\";
		boolean flag = RemoteFile.saveUrlAs(photoUrl, filePath + fileName);
		System.out.println("Run ok!\n Get URL file " + flag);
	}

}

 

myfckconfig.js

FCKConfig.Plugins.Add( 'remoteupload', 'en,zh-cn' ) ;

FCKConfig.ToolbarSets["test"] = [
  ['Source'],
  ['RemoteUpload']
] ;

FCKConfig.RemoteUpload = true ;
FCKConfig.RemoteUploadURL = FCKConfig.BasePath + 'filemanager/remoteupload/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ;

// Edit by lurocky for setUploadFile
FCKConfig.setUploadFile = function( A )
{ 
  if( !A )
  {
    return;
  }
  var B = FCKURLParams['Savepathfilename'];
  if (B) {
    var C = parent.document.getElementsByName( B )[0];
    if ( C ){
      if ( C.value.indexOf( A ) == -1 ) {
        if ( C.value !== "" ){
          C.value = C.value + "|" + A;
        } else {
          C.value = A;
        }
        if ( C.onchange )
        {
          C.onchange();
        }
      }
    }
  }
};

FCKConfig.uploadFileUrl = '';
FCKConfig.getEvalString = function( A )
{
  var B = A.toString();
  return B.substring(B.indexOf("{") + 1, B.lastIndexOf("}"));
};
FCKConfig.FCKLanguageManagerTranslatePageString = FCKConfig.getEvalString(FCKLanguageManager.TranslatePage);
FCKConfig.OnUploadCompleted = function ( errorNumber, fileUrl, fileName, customMsg ) {};
FCKConfig.Ok = function () {};
FCKLanguageManager.TranslatePage = function( A )
{
  eval(FCKConfig.FCKLanguageManagerTranslatePageString);
  var DLwin = A.defaultView || A.parentWindow;
  if (DLwin.OnUploadCompleted) {
    FCKConfig.OnUploadCompleted = DLwin.OnUploadCompleted;
    DLwin.OnUploadCompleted = function ( errorNumber, fileUrl, fileName, customMsg )
    {
      if (fileUrl !== '') {
        FCKConfig.uploadFileUrl = fileUrl;
      }
      return FCKConfig.OnUploadCompleted ( errorNumber, fileUrl, fileName, customMsg );
    };
    if (DLwin.Ok) {
      FCKConfig.Ok = DLwin.Ok;
      DLwin.Ok = function ()
      {
        if (FCKConfig.uploadFileUrl !== '' && FCKConfig.uploadFileUrl == DLwin.GetE('txtUrl').value)
        {
          FCKConfig.setUploadFile(DLwin.GetE('txtUrl').value);
        }
        return FCKConfig.Ok();
      };
    }
  }
};
// Edit end

 

fckplugin.js remoteupload plugin file

 

/*
 * For FCKeditor 2.6
 * 
 * File Name: fckplugin.js
 * 	Add a toolbar button to RemoteUpload.
 * 
 * File Authors:
 * 		lurocky
 */
function splitTextField(objField, html) {
  objField.value = html;
  if (_QuickUploadLanguage != "asp") {
    return;
  }
  var strFieldName = objField.name;
  var objForm = objField.form;
  var objDocument = objField.document;
  var FormLimit = 50000;
  var elements = objDocument.getElementsByName(strFieldName);
  for (var i = 1; i < elements.length; i++) {
    elements[i].value = "";
  }
  if (html.length > FormLimit) {
    objField.value = html.substr(0, FormLimit);
    html = html.substr(FormLimit);
    while (html.length > 0) {
      var ObjTEXTAREA = objDocument.createElement("<TEXTAREA NAME='" + strFieldName + "'></TEXTAREA>");
      objTEXTAREA.style.display = "none";
      objTEXTAREA.value = html.substr(0, FormLimit);
      objForm.appendChild(objTEXTAREA);
      html = html.substr(FormLimit);
    }
  }
}
var ProcessingMsg = (function () {
  var baseZIndex;
  var processingdiv;

  // The document that holds the dialog.
  var topWindow = window.parent;
  while (topWindow.parent && topWindow.parent != topWindow) {
    try {
      if (topWindow.parent.document.domain != document.domain) {
        break;
      }
      if (topWindow.parent.document.getElementsByTagName("frameset").length > 0) {
        break;
      }
    }
    catch (e) {
      break;
    }
    topWindow = topWindow.parent;
  }
  var topDocument = topWindow.document;
  var getZIndex = function () {
    if (!baseZIndex) {
      baseZIndex = FCKConfig.FloatingPanelsZIndex + 999;
    }
    return ++baseZIndex;
  };
  return {DisplayMainprocessingdiv:function (msg) {
    processingdiv = topDocument.createElement("div");
    var height = 30;
    var width = 200;
    var viewSize = FCKTools.GetViewPaneSize(topWindow);
    var scrollPosition = FCKTools.GetScrollPosition(topWindow);
    var iTop = Math.max(scrollPosition.Y + (viewSize.Height - height - 20) / 2, 0);
    var iLeft = Math.max(scrollPosition.X + (viewSize.Width - width - 20) / 2, 0);
    FCKDomTools.SetElementStyles(processingdiv, {"position":"absolute", "zIndex":getZIndex(), "top":iTop + "px", "left":iLeft + "px", "width":width + "px", "height":height + "px"});
    processingdiv.innerHTML = "<table border=0 cellpadding=0 cellspacing=1 bgcolor='#000000' width='100%' height='100%'><tr bgcolor=#3a6ea5><td><marquee id='msgProcessing' align='middle' behavior='alternate' scrollamount='5' style='font-size:9pt;color:#ffffff'>" + msg + "</marquee></td></tr></table>";
    topDocument.body.appendChild(processingdiv);
    var el = FCK.ToolbarSet.CurrentInstance.GetInstanceObject("frameElement");
    el._fck_originalTabIndex = el.tabIndex;
    el.tabIndex = -1;
  }, HideMainprocessingdiv:function () {
    FCKDomTools.RemoveNode(processingdiv);
    var el = FCK.ToolbarSet.CurrentInstance.GetInstanceObject("frameElement");
    el.tabIndex = el._fck_originalTabIndex;
    FCKDomTools.ClearElementJSProperty(el, "_fck_originalTabIndex");
  }, Getprocessingdiv:function () {
    return processingdiv;
  }};
})();
var RemoteUploadInit = false;
var sEventUploadAfter;
FCK.remoteUpload = function (strEventUploadAfter) {
  if (!FCKConfig.RemoteUpload) {
    return;
  }
  var htmlValue = FCK.GetXHTML();
  if (htmlValue == "") {
    return;
  }
  if (!RemoteUploadInit) {
    var eRemoteUploadDiv = document.createElement("div");
    eRemoteUploadDiv.style.cssText = "position:absolute; display:none;";
    var eRemoteUploadForm = document.createElement("form");
    eRemoteUploadForm.id = "editor_UploadForm";
    eRemoteUploadForm.action = FCKConfig.RemoteUploadURL;
    eRemoteUploadForm.method = "post";
    eRemoteUploadForm.target = "editor_UploadTarget";
    var eRemoteUploadInput, eRemoteUploadIframe;
    if (FCKBrowserInfo.IsIE) {
      eRemoteUploadInput = document.createElement("<input type=\"hidden\" name=\"editor_UploadText\" value=\"\">");
      eRemoteUploadIframe = document.createElement("<iframe name=\"editor_UploadTarget\"></iframe>");
    } else {
      eRemoteUploadInput = document.createElement("input");
      eRemoteUploadInput.name = "editor_UploadText";
      eRemoteUploadInput.type = "hidden";
      eRemoteUploadIframe = document.createElement("iframe");
      eRemoteUploadIframe.name = "editor_UploadTarget";
    }
    eRemoteUploadForm.appendChild(eRemoteUploadInput);
    eRemoteUploadIframe.style.cssText = "position:absolute; display:none; width:0px; height:0px;";
    eRemoteUploadIframe.src = "javascript: void(0);";
    eRemoteUploadDiv.appendChild(eRemoteUploadForm);
    eRemoteUploadDiv.appendChild(eRemoteUploadIframe);
    document.body.appendChild(eRemoteUploadDiv);
    RemoteUploadInit = true;
  }
  if (strEventUploadAfter) {
    sEventUploadAfter = strEventUploadAfter;
  }
  splitTextField(document.getElementsByName("editor_UploadText")[0], htmlValue);
  ProcessingMsg.DisplayMainprocessingdiv(FCKLang["MsgRemoteUploading"]);
  document.getElementById("editor_UploadForm").submit();
};
function remoteUploadOK() {
  ProcessingMsg.HideMainprocessingdiv();
  if (FCK.LinkedField) {
    if (sEventUploadAfter) {
      var sScript = "parent." + sEventUploadAfter;
      if (window.execScript) {
        window.execScript(sScript, "JavaScript");
      } else {
        if (FCKBrowserInfo.IsGecko10) {
          eval.call(window, sScript);
        } else {
          if (FCKBrowserInfo.IsAIR) {
            FCKAdobeAIR.FCKeditorAPI_Evaluate(window, sScript);
          } else {
            if (FCKBrowserInfo.IsSafari || FCKBrowserInfo.IsGecko19) {
              var eScript = document.createElement("script");
              eScript.appendChild(document.createTextNode(sScript));
              document.documentElement.appendChild(eScript);
            } else {
              window.eval(sScript);
            }
          }
        }
      }
      eval("parent." + sEventUploadAfter);
    }
  }
}
function OnUploadCompleted(errorNumber, fileUrl, fileName, customMsg) {
  switch (errorNumber) {
    case 0:	// No errors
    alert("Your file has been successfully uploaded");
    break;
    case 1:	// Custom error
    alert(customMsg);
    return;
    case 101:	// Custom warning
    alert(customMsg);
    break;
    case 201:
    alert("A file with the same name is already available. The uploaded file has been renamed to \"" + fileName + "\"");
    break;
    case 202:
    alert("Invalid file type");
    return;
    case 203:
    alert("Security error. You probably don't have enough permissions to upload. Please check your server.");
    return;
    case 500:
    alert("The connector is disabled");
    break;
    default:
    alert("Error on file upload. Error number: " + errorNumber);
    return;
  }
  if (fileUrl) {
    var fileUrls = fileUrl.split("|");
    for (var i = 0; i < fileUrls.length; i++) {
      if (FCKConfig.setUploadFile) {
        FCKConfig.setUploadFile(fileUrls[i]);
      }
    }
  }
  FCK.SetData(FCKTools.HTMLDecode(customMsg.ReplaceAll(["{\"}"], ["'"])));
  remoteUploadOK();
}
var RemoteUploadCommand = function (command) {
  this.Name = command;
};
RemoteUploadCommand.prototype.Execute = function () {
  FCK.remoteUpload();
};
RemoteUploadCommand.prototype.GetState = function () {
  return FCK_TRISTATE_OFF;
};

// Register the related commands.
FCKCommands.RegisterCommand("RemoteUpload", new RemoteUploadCommand(FCKLang["RemoteUpload"]));

// Create the "RemoteUpload" toolbar button.
var RemoteUploadItem = new FCKToolbarButton("RemoteUpload", FCKLang["RemoteUpload"]);
RemoteUploadItem.IconPath = FCKConfig.PluginsPath + "remoteupload/remoteupload.gif";
FCKToolbarItems.RegisterItem("RemoteUpload", RemoteUploadItem);     // 'RemoteUpload' is the name used in the Toolbar config.

 

 

你可能感兴趣的:(java,.net,servlet,fckeditor,asp.net)