本文執行個體講述了JSP下載伺服器檔案的方法。分享給大家供大家參考,具體如下:
<%@page import="java.io.FileInputStream"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><%@page language="java" contentType="text/html; charset=UTF-8"%><%@page import="com.ecc.emp.core.Context" %><%@page import="java.io.File" %><%@ include file="http://www.xxxx.com/head.jsp"%><% boolean loadFlag = false; ServletOutputStream ou = null; FileInputStream fis = null; try{ Context context=(Context)request.getAttribute("context"); String accountFilePath = (String)context.getDataValue("accountFilePath"); //String accountFilePath ="E:/ComeBack/Acc_BOS_CM/WebContent/upload/product/1336873410414custormerStatement.txt"; //String accountFileName = (String)context.getDataValue("accountFileName"); String displayFileName = (String)context.getDataValue("displayFileName"); //String displayFileName ="custormerStatement.txt"; String fullPath =accountFilePath; response.reset(); response.setContentType("charset=UTF-8"); response.setContentType("text/HTML"); //response.setContentType("application/vnd.ms-excel"); String filename = new String(displayFileName.getBytes("gb2312"), "ISO8859-1"); response.setHeader("Content-Disposition","attachment; filename=" + filename); //解決HTTPS不能下載的問題 response.setHeader("Cache-Control","public"); ou = response.getOutputStream(); File file = new File(fullPath); fis = new FileInputStream(file); try { if (fis != null) { int filelen = fis.available(); byte a[] = new byte[filelen]; fis.read(a); ou.write(a); ou.flush(); } loadFlag=true; } catch (Exception e) { System.out.println("Excel is not exist!"); } out = pageContext.pushBody(); }catch(Exception e){ e.printStackTrace(); }finally{ try { fis.close(); ou.close(); ou = null; response.flushBuffer(); } catch (Exception e) { // TODO 自動產生 catch 塊 e.printStackTrace(); } }%>
希望本文所述對大家JSP程式設計有所協助。