- 浏览: 172784 次
- 性别:
- 来自: 广州
-
文章分类
最新评论
-
why240829544:
谢谢
Spring Security 2.0.x中文参考文档.pdf -
lzc879141573:
...
Spring Security 2.0.x中文参考文档.pdf -
zpl:
C:\Documents and Settings\Admin ...
导入word到Fckeditor(java实现) -
zpl:
[img][/img] asdfasdfasdfa
导入word到Fckeditor(java实现) -
zhoutao.temp:
Java文件下载的几种方式
Fckeditor默认是带图片上传的功能 但是这不能满足我们的要求 比如说有的版本的Fckeditor有中文乱码的问题,我用的这个Fckediotr上传图片还有Bug,另外也没办法给图片加水印,传上去的图片还是放在工程下的将来会导致图片越来越庞大,怎么办呢? 我们自己动手丰衣足食,把fckeditor改造成我们需要的.
我用的Fckeditor的jar包是2.5版本的 这个版本图片没有中文乱码 另外如果有中文乱码的问题我建议也不要把图片名称改为UUID名称,因为当用户把自己的图片传上去的时候 想点浏览在去找这张图片的时候 他发现上面的那么多的名字根本分不清哪个是他这次传上来的.有人会问那图片名字重复了怎么办呢?Fckeditor已经考虑到这个问题了 他检测到服务器上有这个名字的图片他会自动重命名.废话不多说了我们来看我是怎么干的.
我们要解决的几个问题
1.上传图片放到服务器的一个物理位置而不是工程下.
2.解决Fckeditor2.5版本中图片上传 没有flush的问题
3.增加水印功能.
Fckeditor低版本的时候我们需要重写一个Servlet 但是我发现这个版本图片上传功能是放在一个类下的而不是
旧版本中的ConnectorServlet.那既然需要重写一个类 而这个类呢有是ConnectorServlet中调用的那我们是不是得先重写ConnectorServlet 然后在重写这个类,然后再把自己写的ConnectorServlet配置到web.xml中呢?不用那么麻烦我不是那样做的 看下图我是怎么做的 ,并请大家自己思考为什么可以这么做.
我在工程下建了和fckeditor相同的包结构然后把我需要重写的类从Fckeditor源代码中拷了过来
好了 我们开始修改吧
Dispatcher.java中doPost方法
- UploadResponse doPost(final HttpServletRequest request) {
- logger.debug("Entering Dispatcher#doPost");
- //String type = null;
- Context context = ThreadLocalData.getContext();
- context.logBaseParameters();
- UploadResponse uploadResponse = null;
- // check permissions for user actions
- if (!RequestCycleHandler.isEnabledForFileUpload(request))
- uploadResponse = UploadResponse.getFileUploadDisabledError();
- // check parameters
- else if (!Command.isValidForPost(context.getCommandStr()))
- uploadResponse = UploadResponse.getInvalidCommandError();
- else if (!ResourceType.isValidType(context.getTypeStr()))
- uploadResponse = UploadResponse.getInvalidResourceTypeError();
- else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
- uploadResponse = UploadResponse.getInvalidCurrentFolderError();
- else {
- // call the Connector#fileUpload
- ResourceType type = context.getDefaultResourceType();
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload upload = new ServletFileUpload(factory);
- try {
- List<FileItem> items = upload.parseRequest(request);
- // We upload just one file at the same time
- FileItem uplFile = items.get(0);
- // Some browsers transfer the entire source path not just the
- // filename
- String fileName = FilenameUtils.getName(uplFile.getName());
- logger.debug("Parameter NewFile: {}", fileName);
- // check the extension
- if (type.isNotAllowedExtension(FilenameUtils
- .getExtension(fileName)))
- uploadResponse = UploadResponse.getInvalidFileTypeError();
- // Secure image check (can't be done if QuickUpload)
- else if (type.equals(ResourceType.IMAGE)
- && PropertiesLoader.isSecureImageUploads()
- && !UtilsFile.isImage(uplFile.getInputStream())) {
- uploadResponse = UploadResponse.getInvalidFileTypeError();
- } else {
- String sanitizedFileName = UtilsFile
- .sanitizeFileName(fileName);
- //修改为UUID文件名称 我这里注释掉了 如下代码可以把上传的图片名称改为UUID
- //sanitizedFileName = UUID.randomUUID().toString()+sanitizedFileName.substring(sanitizedFileName.lastIndexOf("."), sanitizedFileName.length());
- logger.debug("Parameter NewFile (sanitized): {}",
- sanitizedFileName);
- String newFileName = connector.fileUpload(type, context
- .getCurrentFolderStr(), sanitizedFileName, uplFile
- .getInputStream());
- String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler
- .getUserFilesPath(request), type, context
- .getCurrentFolderStr(), newFileName);
- //Fckeditor上传有两种 一种是上传图片 一种是上传附件
- //如果是图片的话 我用这个action来预览图片
- if(type.equals(ResourceType.IMAGE))
- {
- fileUrl = "tumbnail.action?fileName="+sanitizedFileName;
- }
- //如果是上传附件的话 用如下的action来下载附件
- else if(type.equals(ResourceType.FILE)){
- sanitizedFileName = URLEncoder.encode(sanitizedFileName, "utf-8");
- fileUrl = request.getContextPath()+"/attachmentDownload.action?fileName="+sanitizedFileName;
- }
- if (sanitizedFileName.equals(newFileName))
- uploadResponse = UploadResponse.getOK(fileUrl);
- else {
- uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
- logger.debug("Parameter NewFile (renamed): {}",
- newFileName);
- }
- }
- uplFile.delete();
- } catch (InvalidCurrentFolderException e) {
- uploadResponse = UploadResponse.getInvalidCurrentFolderError();
- } catch (WriteException e) {
- uploadResponse = UploadResponse.getFileUploadWriteError();
- } catch (IOException e) {
- uploadResponse = UploadResponse.getFileUploadWriteError();
- } catch (FileUploadException e) {
- uploadResponse = UploadResponse.getFileUploadWriteError();
- }
- }
- logger.debug("Exiting Dispatcher#doPost");
- return uploadResponse;
- }
UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); //String type = null; Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isEnabledForFileUpload(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isNotAllowedExtension(FilenameUtils .getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile .sanitizeFileName(fileName); //修改为UUID文件名称 我这里注释掉了 如下代码可以把上传的图片名称改为UUID //sanitizedFileName = UUID.randomUUID().toString()+sanitizedFileName.substring(sanitizedFileName.lastIndexOf("."), sanitizedFileName.length()); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context .getCurrentFolderStr(), sanitizedFileName, uplFile .getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler .getUserFilesPath(request), type, context .getCurrentFolderStr(), newFileName); //Fckeditor上传有两种 一种是上传图片 一种是上传附件 //如果是图片的话 我用这个action来预览图片 if(type.equals(ResourceType.IMAGE)) { fileUrl = "tumbnail.action?fileName="+sanitizedFileName; } //如果是上传附件的话 用如下的action来下载附件 else if(type.equals(ResourceType.FILE)){ sanitizedFileName = URLEncoder.encode(sanitizedFileName, "utf-8"); fileUrl = request.getContextPath()+"/attachmentDownload.action?fileName="+sanitizedFileName; } if (sanitizedFileName.equals(newFileName)) uploadResponse = UploadResponse.getOK(fileUrl); else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
AbstractLocalFileSystemConnector.java 中 fileUpload方法
- public String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException {
- String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest()));
- File typeDir = getOrCreateResourceTypeDir(absolutePath, type);
- File currentDir = new File(typeDir, currentFolder);
- if (!currentDir.exists() || !currentDir.isDirectory())
- throw new InvalidCurrentFolderException();
- File newFile = new File(currentDir, fileName);
- File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile());
- OutputStream outputStream = null;
- try {
- outputStream = new FileOutputStream(fileToSave);
- IOUtils.copyLarge(inputStream, outputStream);
- } catch (IOException e) {
- throw new WriteException();
- } finally {
- try {
- if (outputStream != null) {
- //这里解决这个版本中图片上传没有flush的bug
- outputStream.flush();
- IOUtils.closeQuietly(outputStream);
- }
- IOUtils.closeQuietly(inputStream);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- String format = fileToSave.getName().substring(fileToSave.getName().lastIndexOf(".") + 1, fileToSave.getName().length());
- //下面给图片加水印
- //如果是图片的话 加水印
- if (ImageUtils.isPicture(format)) {
- ImageUtils.pressImage(servletContext.getRealPath("themes/cms/image/") +"\\"+ "sxgajj.png", newFile.getAbsoluteFile().getAbsolutePath());
- }
- return fileToSave.getName();
- }
public String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException { String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest())); File typeDir = getOrCreateResourceTypeDir(absolutePath, type); File currentDir = new File(typeDir, currentFolder); if (!currentDir.exists() || !currentDir.isDirectory()) throw new InvalidCurrentFolderException(); File newFile = new File(currentDir, fileName); File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile()); OutputStream outputStream = null; try { outputStream = new FileOutputStream(fileToSave); IOUtils.copyLarge(inputStream, outputStream); } catch (IOException e) { throw new WriteException(); } finally { try { if (outputStream != null) { //这里解决这个版本中图片上传没有flush的bug outputStream.flush(); IOUtils.closeQuietly(outputStream); } IOUtils.closeQuietly(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String format = fileToSave.getName().substring(fileToSave.getName().lastIndexOf(".") + 1, fileToSave.getName().length()); //下面给图片加水印 //如果是图片的话 加水印 if (ImageUtils.isPicture(format)) { ImageUtils.pressImage(servletContext.getRealPath("themes/cms/image/") +"\\"+ "sxgajj.png", newFile.getAbsoluteFile().getAbsolutePath()); } return fileToSave.getName(); }
另外还有图片预览的action 和 加水印的代码
图片预览的action代码
- public class FckImgPreviewAction {
- private String fileName;
- public String execute() {
- if (fileName != null) {
- //图片在服务器上的物理存放路径
- String path = ResourceBundle.getBundle("sysConfig").getString("userFilePath.image");
- File file = new File("/" + path + fileName);
- HttpServletResponse resp = ServletActionContext.getResponse();
- OutputStream os = null;
- InputStream is = null;
- if (file.exists()) {
- try {
- is = new FileInputStream(file);
- os = resp.getOutputStream();
- IOUtils.copyLarge(is, os);
- } catch (IOException e) {
- e.printStackTrace();
- }finally{
- try {
- IOUtils.closeQuietly(is);
- if(os != null)
- {
- os.flush();
- IOUtils.closeQuietly(os);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return null;
- }
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- }
public class FckImgPreviewAction { private String fileName; public String execute() { if (fileName != null) { //图片在服务器上的物理存放路径 String path = ResourceBundle.getBundle("sysConfig").getString("userFilePath.image"); File file = new File("/" + path + fileName); HttpServletResponse resp = ServletActionContext.getResponse(); OutputStream os = null; InputStream is = null; if (file.exists()) { try { is = new FileInputStream(file); os = resp.getOutputStream(); IOUtils.copyLarge(is, os); } catch (IOException e) { e.printStackTrace(); }finally{ try { IOUtils.closeQuietly(is); if(os != null) { os.flush(); IOUtils.closeQuietly(os); } } catch (IOException e) { e.printStackTrace(); } } } } return null; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
- /**
- * @param pressImg 水印文件路径
- * @param targetImg 目标文件路径
- */
- public final static void pressImage(String pressImg, String targetImg) {
- FileOutputStream out = null;
- try {
- File _file = new File(targetImg);
- Image src = ImageIO.read(_file);
- int wideth = src.getWidth(null);
- int height = src.getHeight(null);
- BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
- Graphics g = image.createGraphics();
- g.drawImage(src, 0, 0, wideth, height, null);
- // 水印文件
- File _filebiao = new File(pressImg);
- Image src_biao = ImageIO.read(_filebiao);
- int wideth_biao = src_biao.getWidth(null);
- int height_biao = src_biao.getHeight(null);
- g.drawImage(src_biao, wideth - wideth_biao, height - height_biao, wideth_biao, height_biao, null);
- // /
- g.dispose();
- out = new FileOutputStream(targetImg);
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
- encoder.encode(image);
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- if(out!=null)
- {
- try {
- out.flush();
- out.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
/** * @param pressImg 水印文件路径 * @param targetImg 目标文件路径 */ public final static void pressImage(String pressImg, String targetImg) { FileOutputStream out = null; try { File _file = new File(targetImg); Image src = ImageIO.read(_file); int wideth = src.getWidth(null); int height = src.getHeight(null); BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(src, 0, 0, wideth, height, null); // 水印文件 File _filebiao = new File(pressImg); Image src_biao = ImageIO.read(_filebiao); int wideth_biao = src_biao.getWidth(null); int height_biao = src_biao.getHeight(null); g.drawImage(src_biao, wideth - wideth_biao, height - height_biao, wideth_biao, height_biao, null); // / g.dispose(); out = new FileOutputStream(targetImg); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); } catch (Exception e) { e.printStackTrace(); }finally{ if(out!=null) { try { out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
还有个重要的类差点忘了 GetResponse.java GetResponse方法
让fck在上传完图片后 fck图片预览图片url正确的显示
- public GetResponse(Command command, ResourceType type,
- String currentFolder, String constructedUrl) {
- try {
- DocumentBuilderFactory factory = DocumentBuilderFactory
- .newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
- document = builder.newDocument();
- } catch (ParserConfigurationException e) {
- throw new RuntimeException(e);
- }
- Element root = document.createElement("Connector");
- document.appendChild(root);
- root.setAttribute("command", command.getName());
- root.setAttribute("resourceType", type.getName());
- Element currentFolderElement = document.createElement("CurrentFolder");
- currentFolderElement.setAttribute("path", currentFolder);
- if(type.equals(ResourceType.IMAGE))
- {
- constructedUrl = "tumbnail.action?fileName=";
- }
- else if(type.equals(ResourceType.FILE)){
- constructedUrl = "attachmentDownload.action?fileName=";
- }
- currentFolderElement.setAttribute("url", constructedUrl);
- //System.out.println(constructedUrl);
- root.appendChild(currentFolderElement);
- }
public GetResponse(Command command, ResourceType type, String currentFolder, String constructedUrl) { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } Element root = document.createElement("Connector"); document.appendChild(root); root.setAttribute("command", command.getName()); root.setAttribute("resourceType", type.getName()); Element currentFolderElement = document.createElement("CurrentFolder"); currentFolderElement.setAttribute("path", currentFolder); if(type.equals(ResourceType.IMAGE)) { constructedUrl = "tumbnail.action?fileName="; } else if(type.equals(ResourceType.FILE)){ constructedUrl = "attachmentDownload.action?fileName="; } currentFolderElement.setAttribute("url", constructedUrl); //System.out.println(constructedUrl); root.appendChild(currentFolderElement); }
ok了 看下效果
相关推荐
**FCKeditor2.4.1版本(JAVA版)配置详解** FCKeditor是一款非常流行的开源HTML文本编辑器,主要用于网页中的内容编辑。在2.4.1版本中,它为JAVA开发人员提供了丰富的功能,使得在Web应用中集成富文本编辑变得简单易...
本文将深入探讨如何配置FCKeditor以实现JSP页面的图片上传功能。 首先,我们需要了解FCKeditor的基本结构。FCKeditor的核心是一个JavaScript库,它在客户端运行,提供一个所见即所得的编辑界面。为了支持图片上传,...
FCKeditor支持多种功能,其中包括我们关注的“远程图片上传”功能。这个特性允许用户直接从互联网上引用图片,无需先下载到本地再上传,极大地提升了工作效率。 首先,我们要理解什么是远程图片上传。在FCKeditor中...
在Java环境下,FCKeditor通常通过Java版的API进行集成,便于在Java应用中实现富文本编辑功能。 源文件"fckeditor-java-2.6-src"包含了FCKeditor 2.6版本的Java源代码,这对于开发者来说是非常宝贵的资源。通过研究...
**FCKeditor配置for Java** FCKeditor是一款流行的开源富文本编辑器,广泛应用于Web开发中,为用户提供类似于Microsoft Word的界面,使用户能够轻松创建和编辑HTML内容。在Java Web开发环境中,集成FCKeditor可以...
对fckeditor 文件上传功能的修改 1.文件上传绝对路径配置 2.文件上传按上传日期保存 3.浏览上传图片文件和flash文件添加预览功能
FCKeditor与Java的整合主要涉及前端编辑器的配置以及后端处理图片上传的功能。以下是对这个主题的详细阐述: 一、FCKeditor简介 FCKeditor是一个开源的JavaScript组件,它提供了类似Microsoft Word的界面,让用户...
FCKEditor 通过一系列的服务端接口来完成图片上传、文件管理等操作。确保这些接口已被正确配置,并且可以在 Java 服务端正确地响应客户端请求。 #### 四、总结 通过上述步骤,你已经成功地将 FCKEditor 2.6.3 ...
- **Java版FCKeditor**:这是FCKeditor的一个特定实现,将编辑器功能与Java服务器端相结合,方便在Java Web应用中使用。 2. **集成步骤** - **下载库文件**:压缩包中的"java-fck"文件包含了FCKeditor的Java接口...
《FCKEditor使用指南.pdf》提供了更详细的FCKEditor使用方法和配置技巧,包括如何配置图片上传、文件管理器以及与其他Java框架的集成策略。 综上所述,FCKEditor在Java中的应用涉及前端编辑器的配置、后台数据处理...
在JSP环境下配置FCKeditor并实现图片上传功能,需要一系列步骤。下面我们将详细介绍这个过程。 首先,我们需要下载FCKeditor的源代码和相关资源。在提供的压缩包中,有两个文件:`fck-实例.rar`和`FCKEditor-说明....
Fckeditor是一款开源的Web富文本编辑器,它为Java开发者提供了一种方便的方式来在Web应用中集成文本编辑功能。这款编辑器支持多种浏览器,并且具有丰富的文本格式化选项,如字体、字号、颜色、对齐方式、插入图片、...
1. **下载与解压**:从官方或者可靠的资源库获取FCKeditor的Java版本,解压缩后得到所需的文件,这些文件包括JavaScript库、CSS样式表、图片和其他资源。 2. **服务器端配置**:在Java项目中,你需要创建一个...
FCKeditor支持图片上传功能,但需要后端提供一个接收上传文件的接口。在Java中,这通常涉及到文件流的读写操作,以及文件的存储路径管理。你需要编写一个Servlet或Controller,处理POST请求,接收到文件后将其保存...
FCKeditor提供了丰富的文本编辑功能,如字体选择、字号调整、颜色设置、列表创建、链接插入、图片上传等,极大地提升了网页编辑的用户体验。 二、FCKeditor Java Demo 2.4.1 这个版本的Demo是FCKeditor与Java技术...
FCKeditor的特点包括支持多种格式的文本样式、图片上传、链接插入等功能,极大地提升了用户在网页上编辑内容的体验。在Java应用中使用FCKeditor,通常需要通过JavaScript与服务器端的Java代码进行交互,处理上传的...
- 功能强大:FCKeditor提供了丰富的编辑功能,包括文本格式化、图片插入、链接管理、表格操作等,使得非技术人员也能轻松创建和编辑网页内容。 - 配置简单:通过配置文件或API,开发者可以自定义编辑器的行为和...
在 Java 端,你需要实现文件上传的功能,包括接收上传请求,处理文件流,保存到服务器指定目录,并返回一个文件 URL 给 FCKEditor,以便编辑器能正确显示上传的文件。 5. **安全考虑** - 过滤 XSS 攻击:富文本...