• Java实现文件下载


    JavaWeb实现文件的下载

    代码编写:

    package com.rong.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URLEncoder;
    
    //文件下载
    public class FileDown extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.要获取下载文件的路径
            String path = "D://Projects//IdeaProjects//javaweb-01-servlet//response//target//classes//Sea.jpg";
            //2.获取下载的文件名
            String filename = path.substring(path.lastIndexOf("//") + 1);
            //3.让浏览器能够支持下载文件,中文名有可能出现乱码(所以要将文件名转为UTF-8格式)
            resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename,"UTF-8"));
            //4.获取下载文件的输入流
            FileInputStream in = new FileInputStream(path);
            //5.创建buffer缓冲区
            int len =0;
            byte[] buffer = new byte[1024];
            //6.获取OutputStream对象
            ServletOutputStream out = resp.getOutputStream();
            //7.将FileOutputStream写入缓冲区,使用OutputStream将缓冲区的内容写到客户端!
            while ((len=in.read(buffer))>0){
                    out.write(buffer,0,len);
            }
            in.close();
            out.close();
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • 相关阅读:
    【Java编程思想】13.字符串
    【Java编程思想】12.通过异常处理错误
    【Java编程思想】10.内部类
    【Java编程思想】11.持有对象
    【Java编程思想】9.接口
    【Java编程思想】8.多态
    【Java编程思想】7.复用类
    【Java编程思想】6.访问权限控制
    【Java编程思想】4.控制执行流程
    Ribbon、Feign、Hystrix使用时的超时时间设置问题
  • 原文地址:https://www.cnblogs.com/whitespaces/p/12342971.html
Copyright © 2020-2023  润新知