0%

Axios js是非常流行的HTTP请求。你可以在Vue js, node js, react js中使用Axios js来启动get, post, put等请求,但如果你需要同样的要求来从API下载文件响应,并使用Axios js来进行下载,那么你如何做到这一点?我会帮你用Axios做文件下载。

Axios HTTP Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
axios({
url: 'http://localhost:8000/api/get-file',
method: 'GET',
responseType: 'blob',
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');

fileLink.href = fileURL;
fileLink.setAttribute('download', 'file.pdf');
document.body.appendChild(fileLink);

fileLink.click();
});

HTML Code

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
<!DOCTYPE html>
<html>
<head>
<title>Download File using Axios Vue JS? - HackTheStuff</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js" integrity="sha256-S1J4GVHHDMiirir9qsXWc8ZWw74PHHafpsHp5PXtjTs=" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
<button @click="onClick()">DownLoad</button>
</div>
<script type="text/javascript">

var app = new Vue({
el: '#app',
methods: {
onClick() {
axios({
url: 'http://localhost:8000/my.pdf',
method: 'GET',
responseType: 'blob',
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');

fileLink.href = fileURL;
fileLink.setAttribute('download', 'file.pdf');
document.body.appendChild(fileLink);

fileLink.click();
});
}
}
})
</script>
</body>
</html>
参考: https://hackthestuff.com/article/how-to-download-file-in-vuejs-using-axios

Java获取文件拓展名的三种方式

原生Java方式

1
2
3
4
5
6
public Optional<String> getExtensionByStringHandling(String filename) {
return Optional.ofNullable(filename)
.filter(f -> f.contains("."))
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
}

特殊情况:

  • 没有拓展名:该函数返回空字符串
  • 只有拓展名(例如.gitignore):返回gitignore

使用Apache Commons IO包下的FilenameUtils.getExtension工具

1
2
3
public String getExtensionByApacheCommonLib(String filename) {
return FilenameUtils.getExtension(filename);
}

使用Guava Library

1
2
3
4
5
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.1.1-jre</version>
</dependency>
1
2
3
public String getExtensionByGuava(String filename) {
return Files.getFileExtension(filename);
}

将UTC(字符串包含TZ的时间)时间转换成本地时间

1
2
3
4
5
6
utc = "2017-07-28T08:28:47.776Z"
UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
utcTime = datetime.datetime.strptime(utc, UTC_FORMAT)
localtime = utcTime + datetime.timedelta(hours=8)
print(localtime)
# 输出:2017-07-28 16:28:47.776000