1. 程式人生 > >Spring MVC 實現檔案下載,解決檔案下載漢字亂碼問題

Spring MVC 實現檔案下載,解決檔案下載漢字亂碼問題

package com.ss.cms.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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


/**
 * 實現檔案下載
 * @author ss
 */
public class CommonDownload {

	/**
	 * 處理單檔案下載方式(用於檔案下載需要保留上傳檔案時的名字)
	 * @param request
	 * @param response
	 * @param storePath 相對上傳路徑+儲存時的檔名(從專案名開始的路徑)
	 * @param realName 上傳時的檔名
	 */
	public void wenjianxiazai(
			HttpServletRequest request,
			HttpServletResponse response, String storePath, String realName) {
		//定義檔案輸出型別
		String contentType = "application/octet-stream";

		response.setContentType("text/html;charset=UTF-8");
		try {
			request.setCharacterEncoding("UTF-8");
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;

			//構建真實路徑
			String ctxPath = request.getSession().getServletContext().getRealPath("");

			//構成下載路徑
			String downLoadPath = ctxPath + storePath;

			long fileLength = new File(downLoadPath).length();

			response.setContentType(contentType);
			response.setHeader("Content-disposition", "attachment; filename=\"" + new String(realName.getBytes("gbk"),"iso-8859-1")+"\"");
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bis.close();
			bos.close();
		} catch (IOException e) {
			System.err.println("CommonDownload:wenjianxiazai出錯啦!  "+e.getMessage());
		}
	}

}