1. 程式人生 > >java 後臺接收 form 下載檔案

java 後臺接收 form 下載檔案

@RequestMapping(value = "/downloadExeclTemp", method = RequestMethod.POST)
	@ResponseBody
	public void downloadExeclTemp(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="id")String id,@RequestParam(value="name")String name) {
		try {
			String filePath = this.getRequest().getServletContext().getRealPath("\\") + "path.xlsx";
			String outFileName = "pd-"+System.currentTimeMillis()+ ".xlsx";
			InputStream is = null;
			File outfile = null;
			OutputStream os = null;
			// 下載檔案
			try {
				outfile = new File(filePath);
				is = new BufferedInputStream(new FileInputStream(filePath));
				// 設定輸出的格式
				response.setContentType("text/html;charset=UTF-8");
				request.setCharacterEncoding("UTF-8");
				response.reset(); // 重置結果集
				String header = request.getHeader("User-Agent").toUpperCase();
				// 針對IE或者以IE為核心的瀏覽器:
				if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
					outFileName = URLEncoder.encode(outFileName, "utf-8");
					outFileName = outFileName.replace("+", "%20"); // IE下載檔名空格變+號問題
				} else {
					// 非IE瀏覽器的處理
					outFileName = new String(outFileName.getBytes(), "ISO8859-1");
				}
				response.addHeader("Content-Disposition",
						"attachment;filename=" + new String(outFileName.replaceAll(" ", ""))); // 返回標頭檔案名
				response.addHeader("Content-Length", "" + outfile.length()); // 返回頭
																				// 檔案大小
				response.setContentType("application/octet-stream"); // 設定資料種類
				// 迴圈取出流中的資料
				byte[] buffer = new byte[1024];
				int len;
				while ((len = is.read(buffer)) > 0) {
					response.getOutputStream().write(buffer, 0, len);
				}
				// 獲取返回體輸出權
				os = new BufferedOutputStream(response.getOutputStream());
				os.write(buffer); // 輸出檔案
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (os != null) {
						os.flush();
						os.close();
					}
					if (is != null) {
						is.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				} 
			}
		} catch (Exception e) {
			logger.error("下載 "+name+" 模板檔案-出錯",e);
			e.printStackTrace();
		}
	}