zoukankan      html  css  js  c++  java
  • java 通用文件下载 excel,pdf,word,jpg

    <%@ page contentType="text/html; charset=GBK" %>
      <%@ page autoFlush="false" %>
      <%@ page import="java.sql.*" %>
      <%@ page import="java.io.*" %>
      <%@ page import="java.util.*" %>
      <%@ page import="java.awt.*" %>
      <%@ page import="java.awt.image.*" %>
      <%@ page import="com.sun.image.codec.jpeg.*" %>
      <%@ page import="com.sun.image.codec.jpeg.*" %>
      <%!
        public static String getcontentType(String pextFileName)  //获得文件扩展名,by gisoracle

       {
          String pext=pextFileName.toLowerCase();
          if (pext.equals(".xls"))
          {
            return "application/vnd.ms-excel";
          }
          if (pext.equals(".doc"))
          {
            return "application/msword";
          }
          if (pext.equals(".txt"))
          {
            return "text/plain";
          }
          if (pext.equals(".pdf"))
          {
            return "application/pdf";
          }
          if (pext.equals(".jpg")||pext.equals(".jpeg"))
          {
            return "image/jpeg";
          }
          if (pext.equals(".ppt"))
          {
            return "application/vnd.ms-powerpoint";
          }
          if (pext.equals(".gif"))
          {
            return "image/gif";
          }
          return "text/html";
        }
    %>
    <%
      String filename =request.getParameter("filename");
      File downFile = new File(filename);
      String fileext=FileOper.getFiletype(downFile);
      System.out.println("fileext="+fileext);
      String contentType1 =getcontentType(fileext);
      System.out.println("contentType1="+contentType1);
      try {
      out.clear();
      response.setContentType(contentType1);
      filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
      response.setHeader("Content-Disposition","attachment; filename=" +downFile.getName());
      response.addHeader("Cache-Control", "no-cache");
      InputStream blobStream = new FileInputStream(downFile);
      ServletOutputStream outStream = response.getOutputStream();
      byte[] buffer = new byte[10 * 1024];
      int nbytes = 0;
      while ( (nbytes = blobStream.read(buffer)) != -1) {
      outStream.write(buffer, 0, nbytes);
      }
      outStream.flush();
      outStream.close();
      blobStream.close();
      }
      catch (Exception e) {
      System.out.println(e);
      }
    %>

    调用方法:location.href="downfile.jsp?filename="+str;

  • 相关阅读:
    正则表达式
    python最新版mplfinance中文乱码解决方法
    Python学习笔记:pandas.read_csv分块读取大文件(chunksize、iterator=True)
    pandas,读取或存储DataFrames的数据到mysql中
    BaoStock:使用python的baostock接口,查询季频盈利能力
    win10解决Mysql net start mysql启动,提示发生系统错误 5 拒绝访问
    mysql5.7 本地计算机上的mysql 服务启动后停止 的问题
    获取A股所有的股票代码
    phpcms <= v9.15 任意文件读取漏洞的分析和利用
    ubuntu系统安装搜狗法并设置不能切换的问题解决
  • 原文地址:https://www.cnblogs.com/gisoracle/p/1520020.html
Copyright © 2011-2022 走看看