先来看实现效果:

 

有一个链接如下:

点击链接下载文件:

 

 

 第一种方法:Servlet实现

 

一、HTML页面部分:

1、HTML页面中的一个链接

<a id="downloadTemplate" style="color:blue" onclick="download();">下载导入模板</a>

 

2、引入JS

function download(){
    downloadTemplate('downloadExel.downloadexcel', 'filename', 'project');
}

/**
 * 用于下载导入模板时的影藏form表单的提交,采用post方式提交
 * @param action action映射地址
 * @param type parameter的名称
 * @param value parameter的值,这里为file的filename
 */
function downloadTemplate(action, type, value){
    var form = document.createElement('form');
    document.body.appendChild(form);
    form.style.display = "none";
    form.action = action;
    form.id = 'excel';
    form.method = 'post';
    
    var newElement = document.createElement("input");  
    newElement.setAttribute("type","hidden");  
    newElement.name = type;
    newElement.value = value;
    form.appendChild(newElement); 
    
    form.submit();
}

 

3、解释上面JS(不是正是代码)

相当于提交一个form,里面如下:

<input type=hidden name="filename" value = "project">

后台可以通过下面代码获得文件名:project

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

(这段是上面js的翻译,不是正式的哦)

 

 

 二、配置部分

配置前台页面和后台交互

 

1、web.xml配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    

    <servlet>
        <servlet-name>downloadServlet</servlet-name>
        <servlet-class>
            com.zit.rfid.app.prms.business.service.servlet.DownloadTemplateServlet
        </servlet-class>
        <load-on-startup>3</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>downloadServlet</servlet-name>
        <url-pattern>*.downloadexcel</url-pattern>
    </servlet-mapping>
</web-app>

 

我这个web.xml不是整个工程的web.xml,只是一个模块的,在你的web.xml加入上面servlet和servlet-mapping里的内容即可

 

如上:

(1)接受 *.downloadexcel 的Action

(2)HTML的JS里的Action,交给com.test.DownloadTemplateServlet这个类去处理

 

 

2、WebContent目录下新建file文件夹,存放project.xls文件   (Eclipse的Web工程有WebContent,MyEclipse好像是WebRoot)

 

 

三、后台部分

1、新建一个servlet:  

DownloadTemplateServlet.java

package com.test;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author 0223000218
 *    主要用于下载导入模板,页面上传入的request中parameter中,filename代表了要下载的模板的名称
 */
public class DownloadTemplateServlet extends HttpServlet {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -4541729035831587727L;

    private final static String HOME_PATH = DownloadTemplateServlet.class.getResource("/").getPath();
    private final static String DOWNLOAD_TEMP_FILE = HOME_PATH.subSequence(0, HOME_PATH.indexOf("WEB-INF")) + "file/";
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String filename = req.getParameter("filename");
        try{
            resp.reset();// 清空输出流
            
            String resultFileName = filename + System.currentTimeMillis() + ".xls";
            resultFileName = URLEncoder.encode(resultFileName,"UTF-8");  
            resp.setCharacterEncoding("UTF-8");  
            resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
            resp.setContentType("application/msexcel");// 定义输出类型
            //输入流:本地文件路径
            DataInputStream in = new DataInputStream(
                    new FileInputStream(new File(DOWNLOAD_TEMP_FILE + filename + ".xls")));  
            //输出流
            OutputStream out = resp.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];  
            while ((bytes = in.read(bufferOut)) != -1) {  
                out.write(bufferOut, 0, bytes);  
            }
            out.close();
            in.close();
        } catch(Exception e){
            e.printStackTrace();
            resp.reset();
            try {
                OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");  
                String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
                writer.write(data); 
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        
    }
    
    
}

 

大致步骤:

1. 获取服务器文件所在路径

2. 输入服务器文件

3. 输出文件到本地

 

 

 

第二种方法:SpringMVC实现

 

这种方法比较简单

 

一、JSP页面部分

和上面一样

<a id="downloadTemplate" style="color:blue" onclick="download();">下载导入模板</a>

 

 

//导出模板下载
    function download(){
        //后台方法、文件类型、文件名
        downloadTemplate('${pageContext.request.contextPath}/cardIssueVehicleInfo/exportVehicleInfo', 'filename', 'test');
    }

    /**
     * 用于下载导入模板时的影藏form表单的提交,采用post方式提交
     * @param action 请求后台方法
     * @param type 文件类型
     * @param value 文件名
     */
    function downloadTemplate(action, type, value){
        var form = document.createElement('form');
        document.body.appendChild(form);
        form.style.display = "none";
        form.action = action;
        form.id = 'excel';
        form.method = 'post';
        
        var newElement = document.createElement("input");  
        newElement.setAttribute("type","hidden");  
        newElement.name = type;
        newElement.value = value;
        form.appendChild(newElement); 
        
        form.submit();
    }

 

 

二、后台部分

@RequestMapping("exportVehicleInfo")
    public void exportVehicleInfo(HttpServletRequest req, HttpServletResponse resp) {
        String filename = req.getParameter("filename");
        DataInputStream in = null;
        OutputStream out = null;
        try{
            resp.reset();// 清空输出流
            
            String resultFileName = filename + System.currentTimeMillis() + ".xls";
            resultFileName = URLEncoder.encode(resultFileName,"UTF-8");  
            resp.setCharacterEncoding("UTF-8");  
            resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
            resp.setContentType("application/msexcel");// 定义输出类型
            //输入流:本地文件路径
            in = new DataInputStream(
                    new FileInputStream(new File(downloadPath + "test.xls")));  
            //输出流
            out = resp.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];  
            while ((bytes = in.read(bufferOut)) != -1) {  
                out.write(bufferOut, 0, bytes);  
            }
        } catch(Exception e){
            e.printStackTrace();
            resp.reset();
            try {
                OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");  
                String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
                writer.write(data); 
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }finally {
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }

 

 posted on 2017-11-27 09:38  布鲁布鲁sky  阅读(77031)  评论(2编辑  收藏  举报