import lombok.SneakyThrows;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class DownloadUtil {
private final static String FIREFOX = "firefox";
@SneakyThrows
public static void downloadChineseFileByOutputStream(HttpServletRequest req, HttpServletResponse response, String path, String fileName) {
String agent = req.getHeader("USER-AGENT").toLowerCase();
//根据浏览器类型处理文件名称 处理火狐浏览器下载文件名乱码
if (agent.toLowerCase().indexOf(FIREFOX) > 0) {
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
} else {
//其他浏览的中文名称编码
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
//设置content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码,否则会出现文件名乱码
response.reset();
response.setHeader("content-disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream");
URL url = new URL(path);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
//设置是否要从 URL 连接读取数据,默认为true
uc.setDoInput(true);
uc.connect();
InputStream in = uc.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
//将缓冲区的数据输出到客户端浏览器
out.write(buffer, 0, len);
out.flush();
}
out.close();
in.close();
}
}
//调用
String[] split = url.split("/");
String name = split[split.length - 1];
DownloadUtil.downloadChineseFileByOutputStream(request, response, url, name);
Java 任意格式文件下载
最新推荐文章于 2023-07-26 16:45:09 发布