栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

javaEE实现文件上传和下载

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/300018.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号