java处理百度编辑器ueditor上传的图片等多媒体文件

来源:互联网 发布:access连接sql server 编辑:程序博客网 时间:2024/06/06 10:41

java处理百度编辑器ueditor上传的图片等多媒体文件

    开发项目过程中,一般会涉及到采用富文本编辑器处理“内容”之类的业务,而这内容中,难免会上传各种图片、视频等。而一般采用的富文本编辑器常见的有ueditor百度编辑器、widgEditor等等。我一般采用的百度编辑器ueditor。虽然ueditor可以对上传的图片进行配置,在下载的ueditor文件夹下找到config.json,就可以进行配置。如下所示:


    一般情况下,如果要求不严格,那就将上传的图片保存那个目录就好了。但是因为考虑到这种情况:“用户频繁上传 很多张图片,假设是10张,最终却只保留了一张,那么这时候服务器保存下来是那10张图片”,原因很简单,因为ueditor会在用户上传图片时就把图片移到你配置好的那个文件夹目录下,所以就出现了上面的情况。

    如果严格考虑这种情况的话,那么就需要对上传的图片进行处理了。本文就是分享如何处理这种情况!

    首先,ueditor会保留上面截图的那个图片上传目录的配置,如:/temporary/2017-07-22/image/xxxxx,这个目录随你配置,然后,不管你在百度编辑器上传了多少图片,我只需要在ueditor的content中去查找实际要保存的image,注意,在content中,你会发现里面的图片存储正是以html格式的<img>开头的,而这正是进行处理的切入点,最后,找到了所有的img标签,就进行移动的处理,移动到我们指定的文件夹目录下,并将真实路径返回替换掉content中相应的img里面的路径。

    好了,下面就是对ueditor的内容content进行处理的代码:

/** * 处理百度编辑器的内容的图片:jsoup进行处理 * author: steadyjack * @param content:百度编辑器的内容 * date: 2017年6月19日 下午10:29:45 */public static String manageUeditorImage(String content) throws Exception{try {if (!Strings.isNullOrEmpty(content)) {Document doc=Jsoup.parse(content);Elements imageList=doc.select("img"); //处理的切入点,找img标签if (imageList!=null && imageList.size()>0) {for(int i=0;i<imageList.size();i++){Element image=imageList.get(i);String oldImage=image.toString();System.out.println("原始图片:"+oldImage);//只会处理在百度编辑器配置好文件夹目录下的图片--可用于防止修改内容时重复处理String charIndex="/temporary";int index=oldImage.indexOf(charIndex);if (index>0) {String srcImage=oldImage.substring(index);String secIndex="\"";String realImagePos=srcImage.substring(0,srcImage.indexOf(secIndex));System.out.println("实际的临时图片的位置: "+realImagePos);String newImagePos=copyFileForUeditor(realImagePos);content = content.replace(realImagePos, newImagePos);}}}}} catch (Exception e) {}return content; //最终经过图片处理后的百度编辑器的内容}

    

   copyFileForUeditor方法的代码如下:
/** * 复制百度编辑器内的图片到指定的文件夹下  * author: steadyjack * date: 2017年6月19日 下午10:16:40 */public static String copyFileForUeditor(String srcPath){String rootPath=FilePath.getSystemRootPath(); //获取系统根路径--可根据自身需要自己写一个String newFolder="";String fileName="";System.out.println("系统根路径: "+rootPath);try {String srcRealPath=rootPath+srcPath;System.out.println("原图所在的路径: "+srcRealPath);File oldFile=new File(srcRealPath);SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");newFolder="/files/ueditor/"+sdf.format(new Date())+"/"; //自己指定的图片最终移到的目录String newFilePath=rootPath+newFolder;createFold(new File(newFilePath));System.out.println("新的图片所在的路径: "+newFilePath);fileName=oldFile.getName();File newFile=new File(newFilePath+fileName);FileCopyUtils.copy(oldFile, newFile);} catch (Exception e) {e.printStackTrace();}return newFolder+fileName;}

其中,FileCopyUtils使用的spring提供的工具类。

    好了,其实,思路通了,也不复杂。上述的代码我也做了相关注释,如果有相关问题的,可以评论留言,或者加入群进行讨论:

Java开源技术交流:583522159     鏖战八方群:391619659  我叫debug


阅读全文
0 0
原创粉丝点击