當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
用Springboot实现文件下载功能
生活随笔
收集整理的這篇文章主要介紹了
用Springboot实现文件下载功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 ApiOperation(value = "下載文件", httpMethod = "GET", notes = "downloadFile", response = String.class)
2 public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
3 String fileName = "zabbix.txt";// 設置文件名
4 if (fileName != null) {
5 //設置文件路徑
6 // String realPath = "D://zabbix_agentd.conf";
7 String realPath = "D:" + File.separator + "zabbix_agentd.conf";
8 File file = new File(realPath , fileName);
9 if (file.exists()) {
10 response.setContentType("application/force-download");// 設置強制下載不打開
11 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設置文件名
12 byte[] buffer = new byte[1024];
13 FileInputStream fis = null;
14 BufferedInputStream bis = null;
15 try {
16 fis = new FileInputStream(file);
17 bis = new BufferedInputStream(fis);
18 OutputStream os = response.getOutputStream();
19 int i = bis.read(buffer);
20 while (i != -1) {
21 os.write(buffer, 0, i);
22 i = bis.read(buffer);
23 }
24 System.out.println("success");
25
26 InetAddress addr = InetAddress.getLocalHost();
27 String ip=addr.getHostAddress(); //獲取本機ip
28 replacTextContent(ip);
29 } catch (Exception e) {
30 e.printStackTrace();
31 } finally {
32 if (bis != null) {
33 try {
34 bis.close();
35 } catch (IOException e) {
36 e.printStackTrace();
37 }
38 }
39 if (fis != null) {
40 try {
41 fis.close();
42 } catch (IOException e) {
43 e.printStackTrace();
44 }
45 }
46 }
47 }
48 }
49 return null;
50 }
51 /**
52 * 替換文本文件中的 指定字符串
53 * @param path
54 * @throws IOException
55 */
56 public void replacTextContent(String ip){
57 try {
58 File file = new File("D:zabbix_agentd.conf");
59 String content = FileUtils.readFileToString(file, "utf-8");
60 //原有的內容
61 String srcStr = "Hostname=192.168.1.177";
62 //要替換的內容
63 String replaceStr ="Hostname"+ ip;
64 // 讀
65 FileReader in = new FileReader(content);
66 BufferedReader bufIn = new BufferedReader(in);
67 // 內存流, 作為臨時流
68 CharArrayWriter tempStream = new CharArrayWriter();
69 // 替換
70 String line = null;
71 while ( (line = bufIn.readLine()) != null) {
72 // 替換每行中, 符合條件的字符串
73 line = line.replaceAll(srcStr, replaceStr);
74 // 將該行寫入內存
75 tempStream.write(line);
76 // 添加換行符
77 tempStream.append(System.getProperty("line.separator"));
78 }
79 // 關閉 輸入流
80 bufIn.close();
81 // 將內存中的流 寫入 文件
82 FileWriter out = new FileWriter(file);
83 tempStream.writeTo(out);
84 out.close();
85 }catch (Exception e) {
86 e.printStackTrace();
87 }
88 }
?
轉載于:https://www.cnblogs.com/fenghh/p/10058306.html
總結
以上是生活随笔為你收集整理的用Springboot实现文件下载功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Alpha 冲刺11——总结
- 下一篇: fetch + async await