• 返回用户提交的图像工具类


      用户在向服务器提交资料时,有时会提交一个图片,为了改善用户体验,我们会在用户提交图片后随之在前端页面上显示用户提交的图片或缩略图。比如,我们在一些考试类的网站上提交报名信息时,就会经常遇到这种情况。下面是一个工具类,可以返回显示用户提交的图片。  

    import javax.servlet.ServletContext;
    /**
     * 工具类,生成基于网站根目录的绝对路径
     */
    public class UtilGetRealPath {
        private static ServletContext servletContextAll;
        //初始化方法,对serlvetContext进行获取
        public static void init(ServletContext servletContext){
            servletContextAll=servletContext;
        }
    
        public  static String getRealPath(String childPath){
            return servletContextAll.getRealPath(childPath);
        }
    }
    -----------------------------------------------------------
    import java.io.File;
    import java.io.IOException;
    /**
     * 工具类,生成用户提交上来的图片文件对象
     */
    public class UtilGenPhotoFile {
        /*
           返回一个String 路径
         */
        public static String genPhotoFilePath(String fileName,String uid){
            //1.选取生成在哪个文件夹
            File dir=new File(UtilGetRealPath.getRealPath("/photoImg/"+uid));
            //2.如果该文件夹不存在,则创建
            if (!dir.exists()) {
                dir.mkdirs();
            }
            return "/photoImg/"+uid+"/"+fileName;
    
        }
        /*
             返回一个File对象
         */
        public static File genPhotoFile(String fileName,String uid) throws IOException {
            //1.选取生成在哪个文件夹
                File dir=new File(UtilGetRealPath.getRealPath("/photoImg/"+uid));
            //2.如果该文件夹不存在,则创建
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //3.选取生成在哪个具体文件
                File photoFile=new File(dir,fileName);
            //4.如果该文件不存在,则创建
            if (!photoFile.exists()) {
                photoFile.createNewFile();
            }
            return photoFile;
        }
    }  
  • 相关阅读:
    oracle EXP导出一张表时使用query参数指定where条件
    Centos7-安装Apache2.4+PHP5.6
    VMWare 14 Workstation Pro 下载与安装
    Mysql的视图、存储过程、函数、索引全解析
    Eclipse Java注释模板设置详解
    Tomcat 80端口 配置及域名访问步骤
    LeetCode——merge-k-sorted-lists
    LeetCode——rotate-list
    LeetCode——jump-game-ii
    LeetCode——jump-game
  • 原文地址:https://www.cnblogs.com/lizhangyong/p/8625819.html
Copyright © 2020-2023  润新知