使用 java 根据 url 下载并重命名文件

字数412 大约花费2分钟

目录

  1. 1. 告诉浏览器新的文件名称
  2. 2. 设置 contentType
  3. 3. 通过 url 读取网络文件的内容并下载文件

根据 url 下载并重命名文件,包含以下操作:

告诉浏览器新的文件名称

使用 response.setHeader 方法,设置 filename,为了使中文文件名称不乱码,需要加 UTF-8 编码,代码如下:

1
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");

设置 contentType

首先,通过 FilenameUtils.getExtension 获取文件后缀,再根据文件后缀设置 contentType,代码中例子为下载 xls 或 xlsx 类型的文件:

1
2
3
String contentType = "xls".equals(FilenameUtils.getExtension(fileName))
? "application/vnd.ms-excel" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.setContentType(contentType);

通过 url 读取网络文件的内容并下载文件

1
2
3
4
5
6
7
8
9
10
11
12
13
InputStream inputStream = new URL(filePath).openStream();
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
try {
byte[] buffer = new byte[inputStream.available()];
int length = inputStream.read(buffer);
while (length > 0) {
outputStream.write(buffer, 0, length);
length = inputStream.read(buffer);
}
} finally {
inputStream.close();
outputStream.close();
}

完整代码如下:

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
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadExcelFile(HttpServletResponse response) throws Throwable {
String filePath=""; // 文件 url
String fileName=""; // 新的文件名称,包含后缀
downloadFile(response, budgetTemplateUrl, fileName);
}

public void downloadFile(HttpServletResponse response, String filePath, String fileName) throws Throwable {
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
String contentType = "xls".equals(FilenameUtils.getExtension(fileName))
? "application/vnd.ms-excel" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.setContentType(contentType);
InputStream inputStream = new URL(filePath).openStream();
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
try {
byte[] buffer = new byte[inputStream.available()];
int length = inputStream.read(buffer);
while (length > 0) {
outputStream.write(buffer, 0, length);
length = inputStream.read(buffer);
}
} finally {
inputStream.close();
outputStream.close();
}
}

谈谈 IT的文章均为原创或翻译(翻译会注明外文来源),转载请以链接形式标明本文地址: http://tantanit.com/shi-yong-java-gen-ju-url-xia-zai-bing-zhong-ming-ming-wen-jian/

谈谈IT

欢迎关注官方微信公众号获取最新原创文章