jsp action中附件下載的寫法

來源:互聯網
上載者:User

標籤:print   lis   system   瀏覽器   util   response   java.net   path   資訊   

 

//一些主要的包和類

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* 下載檔案
* @return
* @throws UnsupportedEncodingException
*/

@Action(value="downloadAttachFile")
public String downloadAttachFile(){
  //從前台傳過來的附件名字:格式是,“2006#系統測試.docx格式"
  String downloadName =wpyId+"#"+attachName;
  //傳入的資料
  System.out.println(downloadName);
  try {
    OutputStream os = this.response.getOutputStream();

          //OutputStream os = this.getResponse().getOutputStream();

    if (Util.isIE(this.request)) //判斷用戶端是否為IE
    {

               //編碼
      downloadName = URLEncoder.encode(downloadName, "UTF-8");
    }
    else
    {
      downloadName = new String(downloadName.getBytes("UTF-8"),"iso-8859-1");
    }
    //設定讓瀏覽器彈出下載對話方塊的Header
    this.response.setContentType("application/x-download");
    this.response.addHeader("Content-Disposition","attachment;filename=\"" + downloadName + "\"");
    this.response.flushBuffer();
    //將前台的資料經過封裝後(加了頭資料,並經過編碼)需要解碼
    String downloadName1 =URLDecoder.decode(downloadName, "UTF-8");
    System.out.println(downloadName1);
    //解碼的結果輸出
    String bgFile=realPath + File.separator + downloadName1;

    FileInputStream fis = new FileInputStream(bgFile);
    Util.copyStrem(fis, os);
    fis.close();
    os.close();
    System.out.println("==========成功了!!===========");
  } catch (IOException e) {

  e.printStackTrace();//在命令列列印異常資訊在程式中出錯的位置及原因
  System.out.println("==========出錯了!!===========");
  }

  return NONE;
}

jsp action中附件下載的寫法

聯繫我們

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