jsp中的下载链接

1、下载链接jsp界面(a链接直接链文件可以看出文件在服务器中的路径,用servlet处理的链接则看不出)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!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>Insert title here</title>
</head>
<body>
<a href="日期My97DatePickerBeta.rar">下载</a>
<br/>
<a href="DownloadServlet?file=1.jpg">下载1</a>
<br/>
<a href="DownloadServlet?file=2.jpg">下载2</a>
</body>
</html>

备注:a链接直接链文件 遇到文件名为中文时会出现404错误,因为中文乱码了,所以找不到文件,解决方案:

在tomcat中指定url编码即可,找到tomcat目录中的conf下的server.xml,然后打开,找到端口的配置的标签位置:

 <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

然后加上URIEncoding="UTF-8"这个配置,重新启动tomcat即可(上面代码我已加上)
摘:http://ykyfendou.iteye.com/blog/2094734

 

2、DownloadServlet处理代码

package com.java.servlet;

import java.io.File;
import java.net.URLEncoder;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求  
        //读取要下载的文件  
        String fileName = request.getParameter("file");
        //获取项目的物理(磁盘)路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        //构造完整的文件路径及文件名
        String filea = path + "/" +  fileName;
        
        System.out.println(filea);
        
        File f = new File(filea);  
        if(f.exists()){  
            FileInputStream  fis = new FileInputStream(f);  
            String filename=URLEncoder.encode(f.getName(),"utf-8"); //解决中文文件名下载后乱码的问题  
            byte[] b = new byte[fis.available()];  
            fis.read(b);  
            response.setCharacterEncoding("utf-8");  
            response.setHeader("Content-Disposition","attachment; filename="+filename+"");  
            //获取响应报文输出流对象  
            ServletOutputStream  out =response.getOutputStream();  
            //输出  
            out.write(b);  
            out.flush();  
            out.close();  
        }
    }

}

 

posted @ 2017-06-02 20:59  空城余梦love  阅读(2207)  评论(0编辑  收藏  举报