用jsp和servlet实现文件上传

1.需要提前准备好的工具:myeclipse

2.jar包:commons-fileupload-1.2.1.jar和commons-io-1.4.jar

3.js:jquery-1.4.2.js

4.jsp:index.jsp

内容如下(只是一个很简单的jsp):

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
        #out{
            border: 1px solid gray;
            width:150px;
            height:20px;
            
        }
        #in{
            width:0%;
            height:20px;
            background: blue;
        }
    </style>
    <script type="text/javascript"
    src="${pageContext.request.contextPath}/js/jquery-1.4.2.js"></script>
    <script type="text/javascript" >
        $(function(){
            $("form").submit(function(){
                window.setInterval(function(){
                    $.get("${pageContext.request.contextPath}/servlet/UploadProgressServlet",function(data){
                        $("#in").width(data);
                    });
                }, 10);
            
            });
        })
    </script>
  </head>
 
  <body>
      <form action="${ pageContext.request.contextPath }/servlet/UploadServlet" method="post" enctype="multipart/form-data">
          <div id="out">
              <div id="in"></div>
          </div>
          用户名<input type="text" name="username"></input>
          密码<input type="password" name="password"></input>
          上传文件<input type="file" name="files"></input>
          <input type="submit" value="提交">
      </form>
  </body>
</html>

注意:这里的form表单必须必须以post提交,并且需要添加一个属性enctype="multipart/form-data"

5.web.xml中需要填写内容如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
 
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>web.UploadServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>UploadProgressServlet</servlet-name>
    <servlet-class>web.UploadProgressServlet</servlet-class>

  </servlet>

6.在src下创建一个包web,包下创建一个类UploadServlet,这里的包名和类名要和servlet-class中对应,一个检测方法为,按住ctrl键鼠标移动到web.UploadServlet上,如果变色,说明书写正确

public class UploadServlet extends HttpServlet {

    public void doGet(final HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建文件上传工厂
        DiskFileItemFactory factory=new DiskFileItemFactory(100,new File(this.getServletContext().getRealPath("WEB-INF/temp")));
        //创建文件上传的核心类
        ServletFileUpload upload=new ServletFileUpload(factory);
        //判断当前表单是否满足enctype=multpart/form-
        if(!upload.isMultipartContent(request)){
            System.out.println("请确认表单提交格式");
            return;
        }
        //单个文件不能超过1m
        upload.setFileSizeMax(1024*1024);
        //总文件不能超过10m
        upload.setSizeMax(10*1024*1024);
        //解决文件上传的乱码问题
        upload.setHeaderEncoding("utf-8");
        upload.setProgressListener(new ProgressListener() {
            
            long begin=System.currentTimeMillis();
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("已经阅读了"+pBytesRead+"字节");
                System.out.println("总共"+pContentLength+"字节");
                System.out.println("正在阅读第"+pItems+"文件");
                long leftBytes=pContentLength-pBytesRead;
                System.out.println("剩余"+leftBytes+"字节");
                long end=System.currentTimeMillis();
                long time=(end-begin)/1000;
                System.out.println("用时"+time+"秒");
                long speed=time==0?0:(pBytesRead)/time/1024;
                System.out.println("上传速度为"+speed+"kb/s");
                double per = pBytesRead * 10000 / pContentLength / 100.0;
                System.out.print("上传百分比" + per + "%。。");
                //剩余时间
                long lefttime = speed == 0 ? 0 : leftBytes /1024 / speed;
                System.out.println("大致剩余时间"+lefttime+"秒");
                request.getSession().setAttribute("progress", per);
            }
        });
        //解析request,将其转化为item的list集合
        try {
            List<FileItem> items = upload.parseRequest(request);
            //遍历集合,如果是普通的参数则打印
            for (FileItem item : items) {
                if(item.isFormField()){
                    String name=item.getFieldName();
                    String value=item.getString("utf-8");
                    System.out.println(name+":"+value);
                }else{
                //处理ie文件名bug
                String fname=item.getName();
                System.out.println("fname"+fname);
//                if(fname.contains("\\")){
//                    fname=fname.substring(fname.lastIndexOf("\\")+1);
//                }
                //处理一样的文件名
                fname=UUID.randomUUID()+"_"+fname;
                //文件分目录处理
                //获取文件名的hash值,转换为16进制
                String hash=Integer.toHexString(fname.hashCode());
                //hash不足8位,补足
                while(hash.length()<8){
                    hash+="0";
                }
                String path="WEB-INFO/upload/";
                //遍历hash字符串,每一位作为一级分目录
                for (int i = 0; i < hash.length(); i++) {
                    path+=hash.charAt(i)+"/";
                }
                //创建分目录
                new File(this.getServletContext().getRealPath(path)).mkdirs();
                //得到输入流
                InputStream in=item.getInputStream();
                //得到输出流,拼接上路径
                OutputStream out = new FileOutputStream(this.getServletContext().getRealPath(path+fname));
                
                //输出数据流
                int i=-1;
                byte[] data=new byte[1024];
                while((i=in.read(data))!=-1){
                    out.write(data, 0, i);
                }
                //关闭流
                out.close();
                in.close();
                //删除缓文件
                item.delete();
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

7.再在同一个包下建一个类叫UploadProgressServlet

public class UploadProgressServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        double per = (Double) request.getSession().getAttribute("progress");
        response.getWriter().write(per+"%");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

这样就可以访问localhost:8080/day01/index.jsp进行访问,当然端口号可能不一样,day01指的是你的项目名


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值