Servlet文件上传与下载

Servlet实现文件上传

注意:

  • 导jar包:commons-fileupload-xxx、commons-io-xxx.jar。
    maven只引入commons-fileupload依赖即可。commons-io自动引入
  • 表单 method 属性应该设置为 POST 方法,不能使用 GET 方法。
  • 表单 enctype 属性应该设置为 multipart/form-data.

上传文件的servlet的dopost方法:

   protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response) throws ServletException, IOException {
        // 判断是否分段发送,如果不是无法处理
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.write("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 创建用于解析上传数据的工具类
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置中文处理编码
        upload.setHeaderEncoding("utf-8");

        // 设置文件夹路径 最好放在webapp外否则每次部署会清空文件夹
        String uploadPath = "D:\\upload";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // 获取表单项
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 遍历表单项
                for (FileItem item : formItems) {
                    if (item.isFormField()) {
                        System.out.println("请求参数名:"+item.getFieldName());
                        // getString 获取普通表单项的值 参数是设置编码
                        System.out.println("请求参数值:"+item.getString("utf-8"));
                    }else {
                    //    文件表单项
                        String fileName = item.getName();
                        String filePath = uploadPath+File.separator+fileName;
                        // 如果要保存路径到数据库 保存filePath即可
                        File storePath = new File(filePath);
                        // 保存的硬盘
                        item.write(storePath);

                        request.setAttribute("msg","文件上传成功");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", e.getMessage());
        }

        request.getRequestDispatcher("massage.jsp").forward(request,response);
    }

参考:https://www.runoob.com/jsp/jsp-file-uploading.html
拓展:
DiskFileItemFactory类的使用:https://www.cnblogs.com/w-wfy/p/6239330.html
JAVA文件上传 ServletFileUpLoad 实例:
https://www.cnblogs.com/liuyangv/p/8298997.html

Servlet文件下载

  • 主要思路是将文件以流的方式读入内存,再以流的形式写到客户端
  • resp.addHeader("Content-Disposition","attachment;filename=" + fileDisplay)以附件方式发送,客户端会自动下载
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/x-download");
        Integer id = Integer.valueOf(req.getParameter("id"));
        TFile file = fileDao.getFileById(id);
        if (file == null) {
            System.out.println("文件不存在");
            return;
        }

        String fileDisplay = file.getFileName();
        fileDisplay = URLEncoder.encode(fileDisplay,"utf-8");
        // 将文件以附件发送客户端会自动下载
        resp.addHeader("Content-Disposition","attachment;filename=" + fileDisplay);


        OutputStream out = null;

        InputStream in =null;

        try {
            in = new FileInputStream(file.getFilePath());
            out = resp.getOutputStream();

            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) != -1) {
                out.write(b,0,i);
            }

            out.flush();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (in != null) {
                in.close();
            }

        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值