使用java根据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();
}
}
© 2022 谈谈IT All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero