美文网首页
javaWeb实现文件下载

javaWeb实现文件下载

作者: 相信灬你一直在 | 来源:发表于2018-07-20 15:04 被阅读0次
    今天学习了JavaWeb实现文件下载,为了以后方便查找并让需要的人学习,今儿把代码献上!!!! 大笑

    首先写一个jsp页面

    字体加粗的为主要内容:

    download.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>文件下载</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        
      </head>
      
      <body>
        <a href="/download/DownloadServlet?filename=1.jpg">文件下载</a>
      </body>
    </html>
    

    然后在定义一个Servlet,如下:

    DownloadServlet:

        public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
                
                response.setCharacterEncoding("UTF-8");
                //设置ContentType字段值
                response.setContentType("text/html;charset=utf-8");
                //获取所要下载的文件名称
                String filename = request.getParameter("filename");
                //下载文件所在目录
                String folder = "/filename/";
                //通知浏览器以下载的方式打开
                response.addHeader("Content-type", "appllication/octet-stream");
                response.addHeader("Content-Disposition", "attachment;filename="+filename);
                //通知文件流读取文件
                InputStream in = getServletContext().getResourceAsStream(folder+filename);
                //获取response对象的输出流
                OutputStream out = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                //循环取出流中的数据
                while((len = in.read(buffer)) != -1){
                    out.write(buffer,0,len);
                }
                
                
            }
    

    用到的架包:commons-fileupload-1.3.1.jar、commons-io-2.4.jar

    本例子中用到的架包下载地址:http://commons.apache.org/

    相关文章

      网友评论

          本文标题:javaWeb实现文件下载

          本文链接:https://www.haomeiwen.com/subject/xtqqmftx.html