博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jsp如何实现下载文件的功能
阅读量:5903 次
发布时间:2019-06-19

本文共 3937 字,大约阅读时间需要 13 分钟。

hot3.png

 

第一步:创建Servlet   

第二步:写代码

public class FielDownLoad extends HttpServlet {

/**

* Constructor of the object.
*/
public FielDownLoad() {
   super();
}

/**

* Destruction of the servlet. <br>
*/
public void destroy() {
   super.destroy(); // Just puts "destroy" string in log
   // Put your code here
}

/**

* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

   doPost(request, response);

}

/**

* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

   String filename = request.getParameter("file_name");

        
         if (filename == null)
             filename = "";
        
         filename = filename.trim();

         InputStream inStream = null;

         String attchname = "";

         byte[] b = new byte[100];

         int len = 0;
         try {           
             attchname = getAttachName(filename);    //取得附件的名称
             filename = getRealName(request, filename);    //
取得附件的全路径
            
             if (filename == null) {
             response.setContentType("text/html; charset=GBK");
             response.getWriter().print("<span style='color:red'>
文件不存在,或者禁止下载!</span>");
               
                 return;
             }
             attchname = toUtf8String(attchname);    //
将文件转码 UTF-8
             inStream = new FileInputStream(filename);
             response.reset();    //
必须reset,否则会出现文件不完整
            
             SmartUpload su = new SmartUpload();    //
新建一个SmartUpload对象
            
             su.initialize(this.getServletConfig(), request, response);    //
初始化
             //
设定contentDispositionnull以禁止浏览器自动打开文件,
             //
保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
             //doc
时,浏览器将自动用word打开它。扩展名为pdf时,
             //
浏览器将用acrobat打开。
             su.setContentDisposition(null);           
             su.downloadFile(filename);        //
下载文件           
            
             //
循环取出流中的数据
             while ((len = inStream.read(b)) > 0) {
                 response.getOutputStream().write(b, 0, len);
             }
             inStream.close();
            
         } catch (Exception e) {
             e.printStackTrace();
         }

}

/**

* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
   // Put your code here
}
//
取得附件的名称
    public static String getAttachName(String filename) {
        if (filename == null)
            return "";
        filename = filename.trim();
        int pos = 0;
       
        pos = filename.lastIndexOf("\\");       
        if (pos > -1) {
            filename = filename.substring(pos + 1);
        }       
       
        pos = filename.lastIndexOf("/");       
        if (pos > -1) {
            filename = filename.substring(pos + 1);
        }
       
        pos = filename.lastIndexOf(File.separator);       
        if (pos > -1) {
            filename = filename.substring(pos + 1);
        }
       
        return filename;
    }

    //UTF8转码

    public static String toUtf8String(String string) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        String s_utf8 = sb.toString();
        sb.delete(0, sb.length());
        sb.setLength(0);
        sb = null;
        return s_utf8;
    }

    //取得下载文件的真实全路径名称

    private String getRealName(HttpServletRequest request, String filename) {
        if (request == null || filename == null)
            return null;
        filename = filename.trim();
        if (filename.equals(""))
            return null;

        String filepath = request.getRealPath(filename);

        if (filepath == null)
            return null;
        File file = new File(filepath);
        if (!file.exists())
            return null;
        return filepath;
    }

}

 

转载于:https://my.oschina.net/lushuifa/blog/282467

你可能感兴趣的文章
java B2B2C Springcloud电子商城系统-Feign基本使用
查看>>
Qtum量子链x2018区块链新经济论坛:区块链基础设施建设发展方向
查看>>
Java反射与hook混用反射某支付的方法
查看>>
前端性能优化 - Resource Hints 资源预加载
查看>>
JavaScript-console的使用_016
查看>>
两种方式设置iframe的高度区别
查看>>
应用后台省电秘籍——低功耗状态下应用如何正常运行?
查看>>
Iterator 和 for...of 循环
查看>>
浮动的label
查看>>
前端工程化
查看>>
关于iOS 11.x微信连wifi流程中,在Portal页无法拉起微信问题的简单记录
查看>>
Python GUI库wxPython官网Hello World示例的逐行解释
查看>>
RE·WORK 巅峰对话:深度学习将彻底改变医疗健康领域
查看>>
计算机网络物理层
查看>>
CUDA学习(九十三)
查看>>
Mysql如何使自增字段重新计算?
查看>>
使用Telnet测试基本POP3服务
查看>>
Flink SQL 功能解密系列 —— 维表 JOIN 与异步优化
查看>>
Codeforces Round #442 (Div. 2) A B
查看>>
封装一个日期时间选择器
查看>>