java 通用檔案下載 excel,pdf,word,jpg

來源:互聯網
上載者:User

<%@ 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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.