Java 從服務器下載文件到本地(頁面、後臺、配置都有)

 

 先來看實現效果:javascript

 

有一個連接以下:java

點擊連接下載文件:web

 

 

 第一種方法:Servlet實現服務器

 

1、HTML頁面部分:app

一、HTML頁面中的一個連接ide

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

 

二、引入JSpost

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();
}

 

三、解釋上面JS(不是正是代碼)url

至關於提交一個form,裏面以下:spa

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

後臺能夠經過下面代碼得到文件名:project.net

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

(這段是上面js的翻譯,不是正式的哦)

 

 

 2、配置部分

配置前臺頁面和後臺交互

 

一、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這個類去處理

 

 

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

 

 

3、後臺部分

一、新建一個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實現

 

這種方法比較簡單

 

1、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();
    }

 

 

2、後臺部分

@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();
                }
            }
        }
        
    }
相關文章
相關標籤/搜索