JavaWeb文件上传功能实现

  1. 首先form表单属性要设置带有文件上传属性的enctype="multipart/form-data"

  2. 带有此条属性的表单在servlet里的getParamter就会获取不到相应的name==value值。所以在带有文件上传功能的表单中,要判断属性的name值是否为文件上传属性。

  3. 具体代码解释如下:
    只看Post方法即可。

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        switch (method) {
        case "message":
            try {
                message(req, resp);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            break;
        default:
            break;
        }
    }

    private void message(HttpServletRequest req, HttpServletResponse resp)
            throws ParseException, IOException {
        // 创建New对象
        News news = new News();
        System.out.println("临时文件的存放位置:--->"
                + System.getProperty("java.io.tmpdir"));
        // 创建Factory对象 可以设置缓冲区大小 以及存储位置
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 判断是否是文件上传类型
        boolean flag = upload.isMultipartContent(req);
        // 如果是文件上传类型
        if (flag) {
            try {
                // 获取所有的表单元素
                List<FileItem> items = upload.parseRequest(req);
                Iterator<FileItem> its = items.iterator();
                // 遍历表单元素
                while (its.hasNext()) {
                    // 获取遍历器
                    FileItem item = its.next();
                    // 判断表单是什么元素
                    if (item.isFormField()) {
                        // 若是普通元素
                        String fieldName = item.getFieldName();
                        switch (fieldName) {
                        case "title":
                            news.setTitle(item.getString("UTF-8"));
                            break;
                        case "time":
                            news.setCreateTime(new SimpleDateFormat("dd/MM/yy")
                                    .parse(item.getString("UTF-8")));
                            break;
                        case "content":
                            news.setContent(item.getString("UTF-8"));
                            break;
                        }
                    } else {
                        // 若是文件元素
                        String uploadPath = req.getSession()
                                .getServletContext().getRealPath("upload/"+System.currentTimeMillis()+"");
                        // 创建upload文件夹
                        File file = new File(uploadPath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        // 获取上传文件的名称
                        String fileName = item.getName();
                        System.out.println(fileName);
                        if (!"".equals(fileName) && null != fileName) {
                            File saveFile = new File(uploadPath, fileName);
                            item.write(saveFile);
                            news.setImg(uploadPath + "\\" + fileName);
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean add = newsSer.add(news);
            if (add) {
                resp.setContentType("text/html;charset=GBK");
                PrintWriter out = resp.getWriter();
                out.print("<meta   http-equiv='Content-Type'   content='text/html;   charset=GBK'>");
                out.print("<script>");
                out.print("alert('新闻添加成功!');");
                out.print("window.location.href='index.jsp'");
                out.print("</script>");
                out.flush();
                out.close();
            } else {
                resp.setContentType("text/html;charset=GBK");
                PrintWriter out = resp.getWriter();
                out.print("<meta   http-equiv='Content-Type'   content='text/html;   charset=GBK'>");
                out.print("<script>");
                out.print("alert('新闻添加失败,请重新添加!');");
                out.print("window.location.href='form_upload.jsp'");
                out.print("</script>");
                out.flush();
                out.close();
            }       
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值