vue实现点击按钮下载某台服务器某路径下文件
时间: 2024-01-28 17:04:40 浏览: 35
要实现点击按钮下载某台服务器某路径下文件,需要使用Vue的组件和axios库。下面是一个实现的示例:
1. 创建一个Vue组件:
```html
<template>
<div>
<button @click="downloadFile">下载文件</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'DownloadFile',
data() {
return {
serverUrl: 'http://your-server-url.com',
filePath: '/path/to/your/file',
};
},
methods: {
downloadFile() {
axios.get(`${this.serverUrl}/download?path=${this.filePath}`, {
responseType: 'blob',
})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.txt');
document.body.appendChild(link);
link.click();
})
.catch(error => {
console.error(error);
});
},
},
};
</script>
```
2. 在组件中定义服务器地址和文件路径。这里假设服务器地址是 `http://your-server-url.com`,文件路径是 `/path/to/your/file`。
3. 在 `downloadFile` 方法中使用 axios 发送获取文件的请求,并将响应的数据转换成 Blob 类型。然后创建一个链接,设置链接的 href 属性为 Blob 对象的 URL,并将链接添加到文档中。最后触发链接的点击事件,弹出下载对话框。
4. 在模板中添加一个按钮,绑定 `downloadFile` 方法。
上面的示例中,文件名是写死的。如果需要动态设置文件名,可以将文件名作为参数传递给 `downloadFile` 方法,然后在创建链接时设置链接的 `download` 属性为文件名。