java web項目下載代碼例子

java web項目下載代碼例子:

1.新建工具類:DownlaodUtils.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

public class DownlaodUtils {
	
	/**
	 * 生成txt文件
	 * @param fileName	txt路徑
	 * @param fileContent	寫入內容
	 */
	public static void writeFile(String fileName, String fileContent)   
	{     
	    try   
	    {      
	        File f = new File(fileName);      
	        if (!f.exists())   
	        {       
	            f.createNewFile();      
	        }      
	        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"gbk");      
	        BufferedWriter writer=new BufferedWriter(write);          
	        writer.write(fileContent);      
	        writer.close();     
	    } catch (Exception e)   
	    {      
	        e.printStackTrace();     
	    }  
	}  
	
	
	
	/**
	 * 打包文件下載
	 * @param files 下載文件集合
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
    public static HttpServletResponse downLoadFiles(List<File> files,
            HttpServletRequest request, HttpServletResponse response,String filepash)
            throws Exception {
        try {
            /**這個集合就是你想要打包的所有文件,
             * 這裏假設已經準備好了所要打包的文件*/
            //List<File> files = new ArrayList<File>();
     
            /**創建一個臨時壓縮文件,
             * 我們會把文件流全部注入到這個文件中
             * 這裏的文件你可以自定義是.rar還是.zip*/
            File file = new File(filepash);
            if (!file.exists()){   
                file.createNewFile();   
            }
            response.reset();
            //response.getWriter()
            //創建文件輸出流
            FileOutputStream fous = new FileOutputStream(file);   
            /**打包的方法我們會用到ZipOutputStream這樣一個輸出流,
             * 所以這裏我們把輸出流轉換一下*/
//            org.apache.tools.zip.ZipOutputStream zipOut 
//                = new org.apache.tools.zip.ZipOutputStream(fous);
           ZipOutputStream zipOut 
            = new ZipOutputStream(fous);
            /**這個方法接受的就是一個所要打包文件的集合,
             * 還有一個ZipOutputStream*/
           	zipFile(files, zipOut);
            zipOut.close();
            fous.close();
           return downloadZip(file,response);
        }catch (Exception e) {
                e.printStackTrace();
            }
            /**直到文件的打包已經成功了,
             * 文件的打包過程被我封裝在FileUtil.zipFile這個靜態方法中,
             * 稍後會呈現出來,接下來的就是往客戶端寫數據了*/
           // OutputStream out = response.getOutputStream();
           
     
        return response ;
    }
	
    /**
     * 把接受的全部文件打成壓縮包 
     * @param List<File>;  
     * @param org.apache.tools.zip.ZipOutputStream  
     */
    @SuppressWarnings("rawtypes")
	public static void zipFile(List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }
    
    
    public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
        try {
        // 以流的形式下載文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        } catch (IOException ex) {
        ex.printStackTrace();
        }finally{
             try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return response;
    }
    
    
    /**  
     * 根據輸入的文件與輸出流對文件進行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(File inputFile,
            ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                /**如果是目錄的話這裏是不採取操作的,
                 * 至於目錄的打包正在研究中*/
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向壓縮文件中輸出數據   
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 關閉創建的流對象   
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.action類

/**
	 * 下載功能
	 * @param condition2
	 * @return
	 * No such file or directory
	 */
<span style="white-space:pre">	</span>@Action(value="/downloadfile")
	private String downlaodfile(String conditions) {
		HttpServletRequest request = ServletActionContext.getRequest();
//		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		session.setAttribute("bizno",conditions);
		return "下載成功-";
	}
@Action(value="/downloadfi")
public String nxDownload(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		String bizno=(String)session.getAttribute("bizno");
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		//下載所需文件路徑
		String path=request.getSession().getServletContext().getRealPath("/");
		
		String filenames=path+"wondlaod/"+bizno+".txt";
		File file=new File(filenames);    
		if(!file.exists()) DownlaodUtils.writeFile(filenames," \r\n 生產地址:"+GetProValue.getPro("hosturl")+"\r\n 商戶編號:"+bizno);
		
		List<File> list=new ArrayList<File>();
		File file3=new File(path+"key/"+bizno+GetProValue.getPro("bftpubcerpathname"));
		File file1=new File(path+"key/"+bizno+GetProValue.getPro("merprijkspathname"));
		File file2=new File(path+"wondlaod/"+bizno+".txt");
		list.add(file3);
		list.add(file1);
		list.add(file2);
		try {
			DownlaodUtils.downLoadFiles(list,request,response,path+bizno+".rar");
		} catch (Exception e) {
			System.out.println("進入catch模塊");
		}

		return null;
	}

3.js

/**
 * 下載證書
 */
function downlaodzh(){
	var gl15 = $("#submit_cc").combobox("getText");
	if(gl15 == ''){$.messager.alert('提示','一級商戶號爲必選項!'); return false; }
	if(gl15 == '請選擇') {$.messager.alert('提示','一級商戶號爲必選項!'); return false; }
	if(gl15.indexOf("/")>=0) gl15=gl15.substring(gl15.lastIndexOf('/')+1);
	$.ajax({
		url : 'submitmanage.do?data=0014!'+encodeURIComponent(gl15),
		type : 'GET',
		timeout : 15000,
		async : true,
		cache : false,
		success : function(data) {//返回結果
			var arr=data.isTrue.split("-");//分拆字符串爲數據
			if(arr[0] == "0"){//下標0位置的值爲0表示查詢失敗
				$.messager.alert('提示',arr[1]);
			}else if(arr[0] == "1"){
				$.messager.confirm('提示', '您已長時間未使用系統或由於系統原因,請重新登錄!', function(r){
					if (r) {
						relogin();
					}
				});
			}else{//否則表示查詢成功
				
				downloadFile("http://localhost:18083/w_authen/downloadfi.do");

			}
		},
		error : function(data) {
			//提示並隱藏加載效果
			$.messager.alert('提示','系統異常!');
		}
	});
	
}

function downloadFile(url) {   
    try{ 
        var elemIF = document.createElement("iframe");   
        elemIF.src = url;   
        elemIF.style.display = "none";   
        document.body.appendChild(elemIF);   
    }catch(e){ 
    	
    } 
}

註明:在web項目裏有關下載最容易遇到的一個錯誤:   java.lang.IllegalStateException

造成這個錯誤的原因是:該異常表示,當前對客戶端的響應已經結束,不能在響應已經結束後再向客戶端(緩衝區)輸出任何內容。

     即Servlet規範說明,不能調用 response.getOutStream(),又調用response.getWriter(),無論先調用哪一個,在調用第二個時候應會拋出                        IllegalStateException,因爲在js中,out變量是通過response.getWriter得到的,在程序中即用了response.getOutputStream,又用了out變量,故      出現以上錯誤。

   故此我給出的例子,就是在寫下載的時候,通過2次不同的請求到下載action以達到傳數據給服務器的同時,又可以達到下載效果,方法也許不夠好,但希望能幫助遇到下載問題的朋友。

發佈了25 篇原創文章 · 獲贊 9 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章