Java文件下载工具类 (四种方式)

 

1
FileUtils.java
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package com.cmbchina.ccd.itpm.project.util;
 
import org.slf4j.Logger;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
 
import static org.slf4j.LoggerFactory.getLogger;
 
/**
 * @ClassName FileUtils
 * @Description 文件下载
 * @Author Sue
 * @Create 2020/4/16 9:00
 **/
public class FileUtils {
 
    private static final Logger logger = getLogger(FileUtils.class);
 
    public static void download(HttpServletResponse response, String filePath, String encode) {
        response.setContentType("text/html;charset=" + encode);
        String downLoadPath = filePath;
        File file = new File(downLoadPath);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downLoadPath)); BufferedOutputStream bos = new BufferedOutputStream(
                response.getOutputStream())) {
            long fileLength = file.length();
            String fileName = file.getName();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(encode), StandardCharsets.UTF_8));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
 
    /**
     * 以流的方式下载
     *
     * @param path
     * @param response
     * @return
     */
    public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(".".lastIndexOf(filename) + 1).toUpperCase();
            // 以流的形式下载文件。
            byte[] buffer;
            try (InputStream fis = new BufferedInputStream(new FileInputStream(path))) {
                buffer = new byte[fis.available()];
                fis.read(buffer);
            }
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            logger.error("{}", ex);
        }
        return response;
    }
 
    /**
     * 下载本地文件
     *
     * @param response
     * @throws FileNotFoundException
     */
    public void downloadLocal(HttpServletResponse response) throws IOException {
        // 下载本地文件
        // 文件的默认保存名
        String fileName = "Operator.doc";
        // 读到流中
        // 文件的存放路径
        try (InputStream inStream = new FileInputStream("c:/Operator.doc")) {
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inStream.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, len);
                }
            } catch (IOException e) {
                logger.error("{}", e);
            }
        }
 
    }
 
    /**
     * 下载网络文件
     *
     * @throws IOException
     */
    public void downloadNet() throws IOException {
        // 下载网络文件
        int bytesum = 0;
        int byteread;
 
        URL url = new URL("windine.blogdriver.com/logo.gif");
 
        URLConnection conn = url.openConnection();
        try (InputStream inStream = conn.getInputStream(); FileOutputStream fs = new FileOutputStream("c:/abc.gif")) {
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
        }
    }
 
 
    public void downLoadIsOnLine(String fileName, HttpServletRequest request, HttpServletResponse response, boolean isOnLine) throws IOException {
        String absolutePath = fileName;
        File f = new File(absolutePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        //解决中文乱码
        String userAgent = request.getHeader("user-agent").toLowerCase();
        fileName = f.getName();
        String downloadFileName;
 
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            downloadFileName = URLEncoder.encode((fileName), "UTF-8");
        } else {
            downloadFileName = new String((fileName).getBytes(StandardCharsets.UTF_8), "iso-8859-1");
        }
        byte[] buf = new byte[1024];
        int len = 0;
 
        response.reset(); // 非常重要
        // 在线打开方式
        if (isOnLine) {
            URL u = new URL("file:///" + absolutePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + downloadFileName);
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);
        }
 
        try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); OutputStream out = response.getOutputStream()) {
 
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }
 
 
}

  

posted @   少说点话  阅读(6323)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
网站运行:7年51天17时24分19秒
点击右上角即可分享
微信分享提示