SpringMVC的文件上传、下载和验证码

1. 上传(非重点)

1.1 导入jar

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
    <exclusions>
        <exclusion>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

1.2 表单

<form action="${pageContext.request.contextPath }/upload/test1" method="post" 
      enctype="multipart/form-data">
  file: <input type="file" name="source"/> <br>
  <input type="submit" value="提交"/>
</form>

1.3 上传解析器

<!-- 上传解析器 
	     id必须是:“multipartResolver”
 -->
<bean id="multipartResolver" 
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 最大可上传的文件大小   byte 超出后会抛出MaxUploadSizeExceededException异常,可以异常解析器捕获 -->
    <property name="maxUploadSize" value="2097152"></property>
</bean>

1.4 Handler

@RequestMapping("/test1")
public String hello1(String username,MultipartFile source,HttpSession session) {
    //文件的原始名称
    String filename = source.getOriginalFilename();
    //定制全局唯一的命名
    String unique = UUID.randomUUID().toString();
    //【获得文件的后缀】
    String ext = FilenameUtils.getExtension(filename);//abc.txt   txt    hello.html  html
    //定制全局唯一的文件名
    String uniqueFileName = unique+"."+ext;
    System.out.println("唯一的文件名:"+uniqueFileName);

    //文件的类型
    String type = source.getContentType();
    System.out.println("filename:"+filename+" type:"+type);

    //获得 upload_file的磁盘路径 ==> 在webapp目录下创建一个目录"upload_file",且此目录初始不要为空,否则编译时被忽略
    String real_path = session.getServletContext().getRealPath("/upload_file");
    System.out.println("real_path:"+real_path);

    //将上传的文件,存入磁盘路径中
    //source.transferTo(new File("d:/xxxx/xxxx/xx.jpg"))
    source.transferTo(new File(real_path+"\\"+uniqueFileName));
    return "index";
}

2. 下载(非重点)

2.1 超链

<a href="${pageContext.request.contextPath}/download/test1?name=Koala.jpg">下载</a>

2.2 Handler

@RequestMapping("/test1")
public void hello1(String name,HttpSession session,HttpServletResponse response){
    System.out.println("name:"+name);
    //获得要下载文件的绝对路径
    String path = session.getServletContext().getRealPath("/upload_file");
    //文件的完整路径
    String real_path = path+File.separator+name;

    //设置响应头  告知浏览器,要以附件的形式保存内容   filename=浏览器显示的下载文件名
    response.setHeader("content-disposition","attachment;filename="+name);

    //【读取目标文件】,写出给客户端
    IOUtils.copy(new FileInputStream(real_path), response.getOutputStream());

    //上一步,已经是响应了,所以此handler直接是void
}

2.3 上传下载注意事项

2.3.1 数据库保存图片问题

一般我们会将上传的图片打散存储,并赋予新的名称,参考《MVC案例(二)》

如果要将路径存储到数据库,这里建议是【存储带有uuid的图片名称】,因为项目名称或者服务器都会发生变动,一旦发生变动,对应的path就会改变,如果全路径存储,则维护成本会很高。

展示或者下载的时候,重新拼接路径即可找到文件,最好使用【File.separator】,适配微软和其他系统分隔符。

2.3.2 大图片上传异常

如果上传的图片超过【maxUploadSize】的规定大小,应该会报500错误,但也会发生tomcat服务器崩溃问题。解决办法:将maxUpladSize的值调很大;然后设置拦截器进行判断。

public class UploadInterceptor implements HandlerInterceptor{
    private long fileSize;

    public long getFileSize() {
        return fileSize;
    }

    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验文件大小
        ServletRequestContext ctx = new ServletRequestContext(request);
        long realFileSize = ctx.contentLength();//文件大小
        if(fileSize>=realFileSize){
            return true;
        }
        //中断前,响应错误页面
        response.sendRedirect(request.getContextPath()+"/error.jsp");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
<!--web.xml文件配置,在这里限制一个文件的大小-->
	<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/up/**"/>
            <bean class="com.rj.interceptor.UploadInterceptor">
                <property name="fileSize" value="2097152"/>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

3. 验证码(非重点)

屏障,防止暴力破解

3.1 导入jar

<!-- Kaptcha -->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
    <exclusions>
        <exclusion>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

3.2 声明验证码组件

依赖导入,组件在web.xml中声明以后,可以直接使用,不需要创建servlet进行验证码的生成

另外,验证码组件都会默认将验证码放入一个session,以方便后面进行比对验证。

另外,前端获取验证码也只能是【${pageContext.request.contextPath}/captcha】,即captcha

<!--web.xml-->
<servlet>
    <servlet-name>cap</servlet-name>
    <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
    <!--边框-->
    <init-param>
      <param-name>kaptcha.border</param-name>
      <param-value>no</param-value>
    </init-param>
    <!--长度-->
    <init-param>
      <param-name>kaptcha.textproducer.char.length</param-name>
      <param-value>4</param-value>
    </init-param>
    <!--字符池-->
    <init-param>
      <param-name>kaptcha.textproducer.char.string</param-name>
      <param-value>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</param-value>
    </init-param>
    <!--底色-->
    <init-param>
      <param-name>kaptcha.background.clear.to</param-name>
      <param-value>211,229,237</param-value>
    </init-param>
    <!--session.setAttribuite("captcha","验证码")-->
    <init-param>
      <param-name>kaptcha.session.key</param-name>
      <param-value>captcha</param-value>
    </init-param>
  </servlet>
  <!--地址,可以直接访问,返回图片,在线预览-->
  <servlet-mapping>
    <servlet-name>cap</servlet-name>
    <url-pattern>/captcha</url-pattern>
  </servlet-mapping>

3.3 Page

Captcha1是算数验证码;Captcha2是simple验证码验证码,是两个工具类。

Captcha1是算数验证码工具类

/**
 * 算术验证码
 */
public class Captcha1 {
    public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] op = "+-".toCharArray();
        Random r = new Random();
        int index, len1 = op.length;
        int result = 0, firstNum = 0, secondNum = 0;
        char operation = '0';
        String ex="";
        for (int i = 0; i < 4; i++) {// 四次循环,最后生成  【数字1 运算符 数字2 等号】四个部分,如【1 + 2 =】
            if (i != 1) index = r.nextInt(100);
            else index = r.nextInt(len1);

            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            if (i == 0) {
                //g.drawString(index+"", (i*15)+3, 18);
                ex+=index+" ";
                firstNum = index;
            }
            else if (i == 2) {
                //g.drawString(index+"", (i*15)+3, 18);
                ex+=index+" ";
                secondNum = index;
            }
            else if (i == 1) {
                //g.drawString(op[index]+"", (i*15)+3, 18);
                ex+=op[index]+" ";
                operation = op[index];
            }
            else {
                //g.drawString("=", (i*15)+3, 18);
                ex+="=";
            }
        }
        // 绘制算术表达式:ex
        g.drawString(ex,3,18);
        // 计算结果
        if (operation == '+') result = firstNum+secondNum;
        else if (operation == '-') result = firstNum-secondNum;
        else if (operation == '*') result = firstNum*secondNum;
        // 结果存入session
        request.getSession().setAttribute("captcha", result);
        // 写出验证码( 响应请求 )
        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        // 指向客户端的输出流
        ServletOutputStream out = response.getOutputStream();
        // 写出验证码图片,响应
        ImageIO.write(bi, "JPG", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

simple验证码

public class Captcha2 {
    public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//字符集合
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {//验证码长度
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index]+"", (i*15)+3, 18);
            sb.append(ch[index]);
        }
        //存入session
        request.getSession().setAttribute("captcha", sb.toString());
        // 写出验证码( 响应请求 )
        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "JPG", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
@Controller
@RequestMapping("/cap")
public class CaptchaController {

    @RequestMapping("/index")
    public String index() {
        System.out.println("goto captcha.jsp");
        return "WEB-INF/captcha";
    }
	
	//kaptcha验证码组件可不需要创建servlet生成验证码,直接进行使用
    @RequestMapping("/test1")
    public String test1(HttpSession session){
        Object captcha = session.getAttribute("captcha");
        System.out.println("captcha:"+captcha);
        return "index";
    }

    @RequestMapping("/test2")
    public void test2(HttpSession session, HttpServletResponse res, HttpServletRequest req) throws IOException {
        Captcha1.generateCaptcha(req,res);
    }

    @RequestMapping("/test3")
    public void test3(HttpSession session,HttpServletResponse res, HttpServletRequest req) throws IOException {
        Captcha2.generateCaptcha(req,res);
    }


}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <input type="text">
    <img onclick="refreshCode04(this);" src="${pageContext.request.contextPath}/captcha" style="width: 100px;vertical-align: middle">
    <img onclick="refreshCode04(this);" src="${pageContext.request.contextPath}/cap/test2" style="width: 100px;vertical-align: middle">
    <img onclick="refreshCode04(this);" src="${pageContext.request.contextPath}/cap/test3" style="width: 100px;vertical-align: middle">
    <script>
        function refreshCode04(a){
            //刷新验证码
            a.src="${pageContext.request.contextPath}/captcha?"+new Date().getTime();
        }
    </script>
</body>
</html>

<!--验证码校验模版前端-->
<tr>
    <td>验证码:</td>
    <td>
        <input type="text" name="code" id="inputCode">
        <img src="${pageContext.request.contextPath}/cap" onclick="click1(this)"/>
        <div id="yanzhengjieguo" style="color: red"></div>
    </td>
</tr>
<script type="text/javascript">
    function click1(img) {
        img.src="${pageContext.request.contextPath}/cap?" + new Date().getTime();
    }
    $("#inputCode").blur(function () {
        var code = $("#inputCode").val();
        $.ajax({
            url:"${pageContext.request.contextPath}/checkCode",
            type:"get",
            data:{"code":code},
            success:function (data) {
                if(data=='no') {
                    $("#yanzhengjieguo").text("验证码输入错误");
                    $("#denglu").attr("disabled","disabled");
                } else {
                    $("#denglu").removeAttr("disabled");
                    $("#yanzhengjieguo").text("输入正确");
                }
            }
        });
    });
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章