java处理富文本框中的图片,减轻数据库负担

我们在web开发中有时编辑文章,会使用到富文本框,因为特别方便,可以调整文本格式,插入图片等功能。但当保存数据时会发现,插入图片后,图片会以base64位格式存储,这样一张图片根据大小,就会造成该列数据非常的大,在查询的时候会增加查询的时长,速度很慢。这是,如果把插入的图片保存到文件服务器中,只把文件地址保存起来这样就大大减轻了数据库存储的负担,而且查询速度也会很快。下面直接上代码。注另外一篇文件中中将会贴出ftpservice的全部代码

 /**
     * 添加base64图片
     * 处理含有base64位格式的图片,保存为图片并替代为地址
     * @param content
     */
    public String handlerBase64Content(HttpServletRequest request,String parentName,String content) throws Exception{
        if(StringUtil.isNotEmpty(content)){
            //获取src值
            List<String> srcvalues=StringUtil.getImgSrc(content);
            String temp=null;
            for(String src:srcvalues){
                if(src.startsWith("data:image/")){
                    temp=uploadBase64File(request,src,parentName);
                    content=content.replace(src,"SWphotoUrl"+temp);
                }else if(src.contains(parentName)){
                    temp=src.substring(src.indexOf(parentName));
                    content=content.replace(src,"SWphotoUrl"+temp);
                }else{
                    //其他的属于网络图片,不用处理
                }

            }
        }
        return content;
    }

首先获取内容中img标签的属性值

/**
	 * 获取文本中的img标签的src属性值
	 * @param htmlStr
	 * @return
	 */
	public static List<String> getImgSrc(String htmlStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		List<String> pics = new ArrayList<String>();
		String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

获取了图片的base64数据后,进行一系列的处理,然后上传到文件服务器上

/**
     * 上传base64位的图片
     * @param request
     * @param imgStr
     * @param parentName
     * @throws Exception
     */
    private String uploadBase64File(HttpServletRequest request,String imgStr, String parentName) throws Exception{
        String path = request.getSession().getServletContext().getRealPath("")+"/";
        String photoName = GenerateImage(request, imgStr, parentName);
        InputStream is=new FileInputStream(path+photoName);
        String fileName=uploadFile(parentName,is);
        File file=new File(path+photoName);
        if(file.exists()) file.delete();
        return fileName;
    }
    //base64字符串转化成图片
    private String GenerateImage(HttpServletRequest request, String imgStr, String parentName) throws Exception{
        FileHelper fileHelper=new FileHelper();
        //对字节数组字符串进行Base64解码并生成图片
        String imagePath = request.getServletContext().getRealPath("photo")+"/"+parentName;
        fileHelper.mkdir(imagePath);
        //String newfilename=System.currentTimeMillis()+"";
        String newfilename=UUID.randomUUID().toString()+"";
        String filePath=imagePath+"/"+newfilename+".jpg";
        BASE64Decoder decoder = new BASE64Decoder();
        //Base64解码
        imgStr=imgStr.substring(imgStr.indexOf("base64,")+7);
        byte[] b = decoder.decodeBuffer(imgStr);
        for(int i=0;i<b.length;++i)
        {
            if(b[i]<0)
            {//调整异常数据
                b[i]+=256;
            }
        }
        //生成jpeg图片
        fileHelper.createNewFile(filePath);
        OutputStream out = new FileOutputStream(filePath);
        out.write(b);
        out.flush();
        out.close();
        imgStr=null;
        return "photo/"+parentName+"/"+newfilename+".jpg";
    }
     /**
     * 上传文件
     * @param ftpPath
     * @param file
     * @return
     * @throws Exception
     */
    private String uploadFile(String ftpPath,InputStream file) throws Exception{
        String fileName=UUID.randomUUID().toString()+".jpg";
        boolean flag= FtpUtil.uploadFile(S.ftpHost,S.ftpUserName,S.ftpPassword,S.ftpPort,ftpPath,fileName,file);
        if(flag){
            return ftpPath+"/"+fileName;
        }else{
            return null;
        }


    }
     /**
     * Description: 向FTP服务器上传文件
     * @param ftpHost FTP服务器hostname
     * @param ftpUserName 账号
     * @param ftpPassword 密码
     * @param ftpPort 端口
     * @param ftpPath  FTP服务器中文件所在路径 格式: ftptest/aa
     * @param fileName ftp文件名称
     * @param input 文件流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String ftpHost, String ftpUserName,
                                     String ftpPassword, int ftpPort, String ftpPath,
                                     String fileName,InputStream input) {
        boolean success = false;
        FTPClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            //切换到上传目录
            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                //如果目录不存在创建目录
                String[] dirs = ftpPath.split("/");
                String tempPath = "/";
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            return success;
                        } else {
                            ftpClient.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            ftpClient.changeWorkingDirectory(ftpPath);
            ftpClient.setBufferSize(1024*1024);
            ftpClient.storeFile(fileName, input);

            input.close();
            ftpClient.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

所用到的jar包

// ftp
    compile group: 'commons-net', name: 'commons-net', version: '3.3'

FtpUtil工具类


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

public class FtpUtil {

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                System.out.println("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    /*
     * 从FTP服务器下载文件
     *
     * @param ftpHost FTP IP地址
     * @param ftpUserName FTP 用户名
     * @param ftpPassword FTP用户名密码
     * @param ftpPort FTP端口
     * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
     * @param localPath 下载到本地的位置 格式:H:/download
     * @param fileName 文件名称
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserName,
                                       String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                       String fileName) {

        FTPClient ftpClient = null;

        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            File localFile = new File(localPath + File.separatorChar + fileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(fileName, os);
            os.close();
            ftpClient.logout();

        } catch (FileNotFoundException e) {
            System.out.println("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            System.out.println("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件读取错误。");
            e.printStackTrace();
        }

    }

    /**
     * Description: 向FTP服务器上传文件
     * @param ftpHost FTP服务器hostname
     * @param ftpUserName 账号
     * @param ftpPassword 密码
     * @param ftpPort 端口
     * @param ftpPath  FTP服务器中文件所在路径 格式: ftptest/aa
     * @param fileName ftp文件名称
     * @param input 文件流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String ftpHost, String ftpUserName,
                                     String ftpPassword, int ftpPort, String ftpPath,
                                     String fileName,InputStream input) {
        boolean success = false;
        FTPClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            //切换到上传目录
            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                //如果目录不存在创建目录
                String[] dirs = ftpPath.split("/");
                String tempPath = "/";
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            return success;
                        } else {
                            ftpClient.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            ftpClient.changeWorkingDirectory(ftpPath);
            ftpClient.setBufferSize(1024*1024);
            ftpClient.storeFile(fileName, input);

            input.close();
            ftpClient.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    /**
     * 删除文件
     * @param ftpHost
     * @param ftpUserName
     * @param ftpPassword
     * @param ftpPort
     * @param ftpPath
     * @param ftpName
     * @return
     * @throws IOException
     */
    public static boolean deleteFile(String ftpHost, String ftpUserName,
                              String ftpPassword, int ftpPort,String ftpPath,String ftpName) throws IOException{
        boolean flag=true;
        //保存至Ftp
        FTPClient ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
        ftpClient.setControlEncoding("UTF-8"); // 中文支持
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode(); // 用被动模式传输,解决linux服务长时间等待,导致超时问题
        ftpClient.setDefaultTimeout(3000);// 设置默认超时时间
        //切换目录,目录不存在创建目录
        boolean chagenDirFlag=ftpClient.changeWorkingDirectory(ftpPath);
        if(chagenDirFlag==false){
            System.out.println("ftp上目录切换失败");
            return false;
        }
        flag = ftpClient.deleteFile(ftpName);
        if(true==flag){
            System.out.println(ftpName+"   文件删除成功");
        }else{
            System.out.println(ftpName+"   文件删除失败");
        }
        //关闭连接
        ftpClient.logout();
        ftpClient.disconnect();
        System.out.println("FTP文件名——"+ftpName);
        return flag;
    }
}

发布了31 篇原创文章 · 获赞 1 · 访问量 5689

猜你喜欢

转载自blog.csdn.net/wjs040/article/details/91876866
今日推荐