Servlet文件上传

文件上传涉及到的两个Jar包:

  1. com.springsource.org.apache.commons.fileupload
  2. com.springsource.org.apache.commons.io

Html部分

    <!-- form表单提交方式必须为post -->
    <!-- form必须要设置enctype="multipart/form-data"属性,否则后台无法解析 -->
    <form action="/uploading/Uploading" method="post" enctype="multipart/form-data">
        用户:<input type="text" name="username"/><br>
        上传:<input type="file" name="file"/><br>
        <input type="submit" value="提交">
    </form>

Servlet后台处理

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //工厂
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        //解析
        ServletFileUpload sfu = new ServletFileUpload(dfif);
        //解析
        try {
            List<FileItem> fItem = sfu.parseRequest(request);
            FileItem file = fItem.get(1);
            //获取WEB-INF绝对路径
            String path = this.getServletContext().getRealPath("/WEB-INF/files"); 
            System.out.println(path);
            //获取文件名
            String fileName = file.getName();
            //检索文件名是否为绝对路径
            int isExist = fileName.lastIndexOf("\\");
            if(isExist!=-1){
                fileName = fileName.substring(isExist+1);
            }
            //解决文件重名问题
            fileName = UUID.randomUUID().toString()+ "_" + fileName ;
            //获取16进制文件名
            String hashString = Integer.toHexString(fileName.hashCode());
            //创建目录
            File fil = new File(path+"\\"+hashString.charAt(0)+"\\"+hashString.charAt(1));
            fil.mkdirs();
            //创建文件
            File saveFile = new File(fil,fileName);
            //写入文件
            file.write(saveFile);
        } catch (FileUploadException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值