jsp實現下載檔案
阿新 • • 發佈:2018-12-17
js呼叫jsp頁面
window.open("/bfdf/web/DF07?fileName=" + eiInfo.get("fileName"), "_self");
jsp程式碼
<%@page import="java.net.URLDecoder"%> <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ page import="java.io.*" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="styles/basic.css" rel="stylesheet" type="text/css" /> <title>download</title> </head> <% response.setCharacterEncoding("gb2312"); request.setCharacterEncoding("gb2312"); if (request.getParameter("fileName") != null) { OutputStream outStream = null; FileInputStream fileInputStream = null; try { String file = URLDecoder.decode(request.getParameter("fileName"), "UTF-8"); String fileName = file.substring(file.lastIndexOf(File.separator) + 1); if (!(new File(file)).exists()) { System.out.println("沒有檔案"); return; } System.out.println("檔名為:"+file); outStream = response.getOutputStream(); response.setHeader("content-disposition", "attachment;filename=" + fileName); //此項內容隨檔案型別而異 response.setContentType("application/vnd.ms-excel"); byte temp[] = new byte[1000]; fileInputStream = new FileInputStream(file); int n = 0; while ((n = fileInputStream.read(temp)) != -1) { outStream.write(temp, 0, n); } } catch (Exception e) { out.print("出錯"); } finally { if (outStream != null){ outStream.close(); } if (fileInputStream != null){ fileInputStream.close(); } } out.clear(); out = pageContext.pushBody(); } %>
java部分
return file.getAbsolutePath();