jsp页面实现文件的下载

1.  用jsp页面实现了文件的下载:

<%@page language="java" contentType="application/x-msdownload"
	pageEncoding="UTF-8"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.net.URLEncoder"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>下载文件</title>
</head>
<body>
	<%
	    String docname = request.getParameter("docname");

	    String filedisplay = "";
	    //由于href链接不能使用中文,这里根据文件名判断是否需要改为中文
	    if (docname.equals("txt.txt") || docname.equals("word.doc") || docname.equals("excel.xls"))
	    {

	        filedisplay = "好友信息" + docname.substring(docname.lastIndexOf("."));
	    }
	    else
	    {
	        filedisplay = docname;//"给用户提供的下载文件名";   
	    }
	    response.reset();//可以加也可以不加
	    response.setContentType("application/x-download");
	    String paths = pageContext.getServletContext().getRealPath("/");
	    String realPath = paths + "/download/";
	    String filedownload = realPath + docname;

	    filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
	    response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);

	    //此处记得清理下。在释放在jsp中使用的对象时,会调用response.getWriter(),因为这个方法是和response.getOutputStream()相冲突的!
	    out.clear();
	    out = pageContext.pushBody();

	    OutputStream outp = null;
	    FileInputStream in = null;
	    try
	    {
	        outp = response.getOutputStream();
	        in = new FileInputStream(filedownload);

	        byte[] b = new byte[1024];
	        int i = 0;

	        while ((i = in.read(b)) > 0)
	        {
	            outp.write(b, 0, i);
	        }
	        outp.flush();
	    }
	    catch (Exception e)
	    {
	        System.out.println("Download Error!");
	        e.printStackTrace();
	    }
	    finally
	    {
	        if (in != null)
	        {
	            in.close();
	            in = null;
	        }
	        if (outp != null)
	        {
	            outp.close();
	            outp = null;
	        }
	    }
	%>
</body>
</html>


2.添加相关的下载链接,后面跟的参数是下载文件名。例如

<a href="../download/down.jsp?docname=soplus.apk" >下载</a>


转载于:https://my.oschina.net/u/1172409/blog/159249

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值