iframe标签的使用(二)02——vue3.0页面结构的应用 & 文件下载功能-直接定义下载方法
效果-下载
结构
<el-button type="primary" @click='openFile(attachmentUrl, fileName)'>下载</el-button>
实例
<el-dialog v-model="dialogFormVisible" title="题目" width="660px" >
<label>附件:</label>
<span class="color-666666 color-1890ff hand" @click="openFile(url, fileName)">
{{ fileName }}
</span>
</el-dialog>
方法
方式2:直接定义方法
import { defineComponent, reactive, ref, toRefs } from 'vue';
import { downloadFile } from '@/axios';
import { useRoute } from 'vue-router';
export default defineComponent({
name: 'name',
props: [
'state',
],
setup(props, { emit }) {
let dialogFormVisible = ref(false);
const route = useRoute();
const funMethods = {
cancel() {
emit('close');
},
openFile(openFile, fileName) {
if (!openFile) return ElMessage.error('文件地址不存在!');
downloadFile(openFile, fileName);
}
};
return {
dialogFormVisible,
...toRefs(props.state),
...funMethods
};
},
});
封装的下载方法-downloadFile()
src/axios/index.ts
/**
* 下载文件通过DFS url
* @param url
* @param name
* @param params
*/
export const downloadFile = (url: string, name?: string, params?: Object) => {
axios
.get(url, {
params,
responseType: 'blob'
})
.then(res => {
let fileName = '';
//判断是否存在 . 如果不存在说明是自己传入
if (name.indexOf('.') === -1) {
fileName = name;
fileName += url.length
? '.' + url.substring(url.lastIndexOf('.') + 1, url.length)
: '';
} else {
//存在 filename 直接使用
fileName = name;
}
downloadByBlob(res.data, fileName);
});
};
export const downloadByBlob = (blob: Blob, fileName: string) => {
//不建议改这个 post 还有get 流下载都通过这种形式
const b = new Blob([blob],{type:'application/vnd.ms-excel'});
let link = document.createElement('a');
const href = URL.createObjectURL(b);
link.href = href;
link.download = fileName;
link.click();
link = null;
window.URL.revokeObjectURL(href);
};