javaEE实现文件上传和下载

准备工作

因为IO操作很繁琐所以,上传部分选用smartUpload库 所以,项目开始前需要添加Smartupload.jar到项目 完成网页部分。

Upload (smartupload)

@Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
   
	 	// 1 创建上传文件的对象
        SmartUpload smartUpload = new SmartUpload();

        // 2 初始化上传操作
        PageContext pageContext = JspFactory.getDefaultFactory().
                getPageContext(this, req, resp, null, false, 1024, true);

        smartUpload.initialize(pageContext);
        // 2.1 配置编码格式
        smartUpload.setCharset("utf-8");
// 3 上传
        try {
          
   
            smartUpload.upload();
        } catch (SmartUploadException e) {
          
   
            e.printStackTrace();
        }

        // 4 获取文件信息
        File file = smartUpload.getFiles().getFile(0);
        String fileName = file.getFileName();
        String contentType = file.getContentType();

如果需要获取的是文本数据的话,需要用下面代码来实现。因为从表单中获取到的数据是已经被封装到了 smartUpload 中:

//获取文本信息
        String username = smartUpload.getRequest().getParameter("username");
        System.out.println("username = " + username);

下面一段是上传文件的最后一部分。 这部分中的路径名称,需要已经存在该路径,否则服务器报错,路径无法找到。而在 file.saveAs()中指定了File.SAVEAS_VIRTUAL储存在虚拟路径下,即这个路径需要在 out 中能够找到。如果该路径指向project中已存在的 空文件夹,那么在out中可能就不存在这个文件加,则服务器报错路径无法找到。

// 5 指定上传路径
        String uploadPath = "/resources/" + fileName;

        // 6 保存指定地址
        try {
          
   
            file.saveAs(uploadPath, File.SAVEAS_VIRTUAL);
        } catch (SmartUploadException e) {
          
   
            e.printStackTrace();
        }

        // 7 跳转到成功界面
        req.setAttribute("fileName", fileName);
        req.getRequestDispatcher("success.jsp").forward(req, resp);

    }

Download

下载相对于上传来说步骤少得多,话不多说直接上代码:

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
   
        String fileName = req.getParameter("fileName");
        String path = "/resources/" + fileName;
        // System.out.println(path);

        // 设置响应的头信息和响应的类型
        resp.setContentType("application/octet-stream"); // 将响应的内容设置为通用的二进制流
        resp.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8")); // 告诉浏览器以附件的方式下载文件(弹出下载框)

        // 跳转界面
        req.getRequestDispatcher(path).forward(req, resp);
        // 清空缓存
        resp.flushBuffer();
    }
经验分享 程序员 微信小程序 职场和发展