http下載檔案(通用格式) .jsp j ava

來源:互聯網
上載者:User

標籤:http   io   os   java   ar   檔案   art   div   sp   

package com.yqcf.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownFile {
 /**
  *
  * 在jsp頁面調用fileDown(request,response) url傳參:dirPath(檔案的全路徑),fileName(檔案名稱)
  *
  * @return boolean
  */
 public boolean fileDown(HttpServletRequest request,
   HttpServletResponse response) {
  // ************取得檔案的路徑和檔案名稱***************//
  String dirPath = request.getParameter("dirPath");
  String fileName = request.getParameter("fileName");
  // ************判斷檔案是否存在********************//
  File file = new File(dirPath, fileName);
  if (!file.exists()) {
   System.out.println("檔案下載失敗:檔案或路徑錯誤");
   return false;
  }
  long fileLength = file.length();
  String length = String.valueOf(fileLength);
  // 設定返迴文件的類型和頭資訊,application/octet-stream:檔案類型的通用格式//
  response.setContentType("application/octet-stream");
  response.setHeader("Content-disposition", "attachment;filename="
    + fileName);
  response.setHeader("Content_Length", length);
  FileInputStream input = null;
  ServletOutputStream output = null;
  try {
   // **************產生輸入資料流和輸出資料流*************//
   input = new FileInputStream(file);
   output = response.getOutputStream();
   byte[] block = new byte[1024];
   int len = 0;
   // **************開始下載檔案*****************//
   while ((len = input.read(block)) != -1) {
    output.write(block, 0, len);
   }
   output.flush();
   return true;
  } catch (IOException e) {
   System.out.println("檔案下載失敗:" + e.getMessage());
   return false;
  } finally {
   // *************關閉檔案流****************//
   try {
    if (input != null) {
     input.close();
    }
    if (output != null) {
     output.close();
    }
   } catch (IOException ex) {
    System.out.println(ex.getMessage());
   }
  }
 }

}

 

http下載檔案(通用格式) .jsp j ava

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.