JSP下载服务器文件的方法

网络编程 2021-07-05 11:23www.168986.cn编程入门
这篇文章主要介绍了JSP下载服务器文件的方法,涉及JSP文件传输的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了JSP下载服务器文件的方法。分享给大家供大家参考,具体如下

<%@page import="java.io.FileInputStream"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://.w3./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@page language="java" contentType="text/html; charset=UTF-8"%>
<%@page import=".e.emp.core.Context" %>
<%@page import="java.io.File" %>
<%@ include file="http://.xxxx./head.jsp"%>
<%
  boolean loadFlag = false;
  ServletOutputStream ou = null;
  FileInputStream fis = null;
  try{  
    Context context=(Context)request.getAttribute("context");
    String aountFilePath = (String)context.getDataValue("aountFilePath");
    //String aountFilePath ="E:/ComeBack/A_BOS_CM/WebContent/upload/product/1336873410414custormerStatement.txt";
    //String aountFileName = (String)context.getDataValue("aountFileName");
    String displayFileName = (String)context.getDataValue("displayFileName");
    //String displayFileName ="custormerStatement.txt";
    String fullPath =aountFilePath;
    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程序设计有所帮助。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by