一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - JavaWeb響應(yīng)下載功能實(shí)例代碼(包含工具類)

JavaWeb響應(yīng)下載功能實(shí)例代碼(包含工具類)

2020-11-30 15:26ChoviWu Java教程

今天通過本文給大家分享的是關(guān)于javaweb的響應(yīng)(response)下載功能,需要的朋友參考下吧

今天通過本文給大家分享是關(guān)于javaweb的響應(yīng)(response)下載

以下是我的Demo:

頁面我就粘主要部分的代碼

?
1
<a href = "${pageContext.request.contextPath }/user/courseTab">模板下載</a>

當(dāng)然,現(xiàn)在的項(xiàng)目大家都使用框架,這里我使用的是(SSM),好了,粘代碼

?
1
2
3
4
5
6
7
8
9
@Controller
@RequestMapping("/user")
public class UploadController {
@RequestMapping(value="/courseTab",method=RequestMethod.GET)
  public void courseTab(HttpServletResponse response,HttpServletRequest request) throws IOException{
    String path = request.getSession().getServletContext().getRealPath("/courseTab/課表上傳模板.xls");
    DownUtil.downMb(response, path, "課表模板"+DateFormat.formatSimple(new Date()));
}
}

 這里我使用的DownUtil工具類是我自己寫的,下來我粘到文章中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package org.cxxy.base.cxsc.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
/**
 * @Title: DownUtil.java
 * @Package org.cxxy.base.cxsc.util
 * @Description:文件下載工具類
 * @author ChoviWu
 * @date 2017年6月18日 下午2:44:17
 * @version V1.0
 */
public class DownUtil {
  /**
   *
   * @Description:
   * @param @param response
   * @param @param url 文件在數(shù)據(jù)庫的路徑
   * @param @param base 文件存放的基礎(chǔ)路徑
   * @param @param folderPath 上傳所在的文件夾
   * @param @return
   * @param @throws IOException
   * @return int
   * @throws
   */
  @SuppressWarnings("unused")
  public static int downFile(HttpServletResponse response, String url,
      Integer down, String base, String folderPath) throws IOException {
    // 文件的名稱
    String fileName = url.split("/")[1];
    System.out.println(fileName);
    // 文件的后綴
    String last = url.substring(url.lastIndexOf(".") + 1);
    System.out.println(last);
    // 文件路徑
    String downFilePath = base + folderPath + fileName;
    Long fileLength = new File(downFilePath).length();// 文件的長度
    if (fileLength != 0) {
      response.reset();
      response.setContentType("application/octet-stream;charset=utf-8"); // 改成輸出excel文件
      try {
        response.setHeader(
            "Content-disposition",
            "attachment; filename="
                + new String(fileName.getBytes("utf-8"),
                    "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(downFilePath);
        bis = new BufferedInputStream(fis);
        // 輸出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesread;
        // 寫文件
        while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
          bos.write(buff, 0, bytesread);
        }
        // 跳轉(zhuǎn)的路徑
        fis.close();
        bis.close();
        bos.close();
      } catch (FileNotFoundException e) {
        System.out.println("File is Not Exsist!");
      }
    } else {
      // 拋異常
      response.getWriter()
          .write("<script charset='utf-8' type='text/javascript'>alert('該資源不存在!');history.go(-1);</script>");
      return down;
    }
    down++;
    return down;
  }
  /**
   *
   * @Description: 下載的模板
   * @param @param response
   * @param @param path 路徑名
   * @param @param name 模板名稱
   * @param @throws IOException
   * @return void
   * @throws
   */
  @SuppressWarnings("unused")
  public static void downMb(HttpServletResponse response, String path,
      String name) throws IOException {
    Long fileLength = new File(path).length();// 文件的長度
    System.out.println("文件的長度:" + fileLength);
    if (fileLength != 0) {
      response.reset();
      response.setContentType("application/octet-stream;charset=utf-8"); // 改成輸出excel文件
      try {
        response.setHeader(
            "Content-disposition",
            "attachment; filename="
                + new String(name.getBytes("utf-8"),
                    "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(path);
        bis = new BufferedInputStream(fis);
        // 輸出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesread;
        // 寫文件
        while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
          bos.write(buff, 0, bytesread);
        }
        fis.close();
        bis.close();
        bos.close();
      } catch (FileNotFoundException e) {
        System.out.println("File is Not Exsist!");
      }
    }
  }
}

 下來,我說一下,調(diào)用的downMb,我們都知道,在服務(wù)器上下載一個(gè)文件,

?
1
2
3
4
//設(shè)置響應(yīng)頭,控制瀏覽器下載該文件,形參調(diào)的是文件的長度
response.setHeader("Content-Length", String.valueOf(fileLength));
 //設(shè)置響應(yīng)類型,設(shè)置輸出流類型
response.setContentType("application/octet-stream;charset=utf-8"); // 改成輸出excel文件

 這里我使用的是輸出的Excel文件

接下來就是讀文件,寫文件了,相信學(xué)了java基礎(chǔ)的都會接觸IO吧,這里我就略過

?
1
2
BufferedInputStream bis = null;
BufferedOutputStream bos = null;

這里使用的是緩沖流,因其使用的是瀏覽器打開文件的下載

下來就是寫文件了,寫文件也是一貫的套路,先把文件存到buff數(shù)據(jù)緩沖區(qū),然后將buff的數(shù)據(jù)輸出到瀏覽器供用戶查看

?
1
2
3
4
5
6
byte[] buff = new byte[2048];
  int bytesread;
  // 寫文件
  while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesread);
  }

當(dāng)讀寫完文件之后,千萬別忘了要關(guān)閉文件流(當(dāng)然,關(guān)閉流的順序也不能變)

?
1
2
3
fis.close();
bis.close();
bos.close();

以上所述是小編給大家介紹的JavaWeb響應(yīng)下載實(shí)例代碼(包含工具類),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!

原文鏈接:http://www.cnblogs.com/ChoviWu/archive/2017/07/11/7150070.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 奇米狠狠色 | 国产精品日韩欧美一区二区三区 | 亚洲男人天堂a | 果冻传媒在线视频观看免费 | 精品一产品大全 | 国产精品激情综合久久 | 国产视频三区 | 91美女在线 | 2019天天干夜夜操 | 日本激情网 | 草莓影音| 国产拍拍视频一二三四区 | 欧美精品一线二线大片 | 91青青国产在线观看免费 | 色卡7707c| 99九九精品视频 | 日本不卡视频免费的 | 五月桃花网婷婷亚洲综合 | 日本三级斤 | 美女脱了内裤让男桶爽 | 湖南美女被黑人4p到惨叫 | 91传媒制片厂制作传媒破解版 | 色婷在线| 91亚洲一区二区在线观看不卡 | 国产成人cao在线 | 办公室操秘书 | ass性强迫rape| 天天天天天天天操 | 国产日韩欧美精品在线 | 四虎音影| 俄罗斯男男激情1069gay | 天堂8在线天堂bt | 精品手机在线视频 | 精品一区二区三区五区六区 | 国产在线视频自拍 | 亚洲品质自拍视频网站 | 波多野结衣被绝伦强在线观看 | 色欧美亚洲 | 天美传媒传媒免费观看 | chinese国产人妖hd | 日本高清va不卡视频在线观看 |