A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 冯超 高级黑马   /  2013-9-1 15:03  /  7706 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

                                                                                         jsp实习的文件上传案例
文件上传需要用到:common-fileupload和common-io这两个jar包。
客户端代码:
  1. <form action="<%=path %>/servlet/UploadFileService" method="post" enctype="multipart/form-data">
  2.                    文件:<input type="file" name="file"><br />
  3.                    <input type="submit" value="上传">
  4.              
  5.            </form>
复制代码
服务端代码:
  1. request.setCharacterEncoding("utf-8");
  2.         response.setCharacterEncoding("utf-8");
  3.         response.setContentType("text/html;charset=utf-8");
  4.          
  5.        //1.判断文件上传的是否没有子文件
  6.        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  7.        if(isMultipart) {
  8.           // 2得到存放文件的真实路径
  9.                String realpath = request.getSession().getServletContext().getRealPath("/files");
  10.                System.out.println(realpath);
  11.                File dir = new File(realpath);
  12.                if(!dir.exists()) {
  13.                        dir.mkdirs();
  14.                }
  15.               
  16.                FileItemFactory factory = new DiskFileItemFactory();
  17.                ServletFileUpload upload = new ServletFileUpload(factory);
  18.                upload.setHeaderEncoding("utf-8");
  19.                try {
  20.                       List<FileItem> items = upload.parseRequest(request);
  21.                       for(FileItem item : items) {
  22.                               if(item.isFormField()) {
  23.                                       String name = item.getFieldName();
  24.                                       String value = item.getString("utf-8");
  25.                                       System.out.println(name + "=" + value);
  26.                               }
  27.                               else {
  28.                                       item.write(new File(dir,item.getName().toString()));
  29.                               }
  30.                       }
  31.                } catch (Exception e) {
  32.                        // TODO Auto-generated catch bloc
  33.                        e.printStackTrace();
  34.                }
  35.               
  36.        } else {
  37.                System.out.println("该文件不能上传");
  38.        }
复制代码

6 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报

兄台 抬举了
回复 使用道具 举报
终于找到想要的了,赞一个:handshake
回复 使用道具 举报
1003771635 发表于 2014-5-26 19:27
终于找到想要的了,赞一个

学了Struts2没有
  Struts2上传文件更爽,直接取得File文件内容 文件类型 文件名称,你只需要做的就是刚该File内容通过inputStream读取在通过outPutStream写入你要放置的文件夹就可以了!@
回复 使用道具 举报
冯超 发表于 2014-5-27 10:58
学了Struts2没有
  Struts2上传文件更爽,直接取得File文件内容 文件类型 文件名称,你只需要做的就是刚 ...

哦,还没学
回复 使用道具 举报
qfch 中级黑马 2014-6-5 19:40:09
7#
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马