文件下载功能
结构
<label>附件:</label><span
class='pointer color-1890ff' @click='openFile(attachmentUrl, fileName)'>{{ fileName }}</span
>
逻辑1-不抽离写法
<script lang='ts'>
import {downloadFile} from '@/axios';
import {defineComponent, reactive, toRefs} from 'vue';
export default defineComponent({
name: 'index',
components: {},
setup(props, context) {
const router = useRouter();
const route = useRoute();
const funMethods = {
// 查看详情
handleDetails(row) {
router.push({
path: 'screen',
query: {
resumeId: row.resumeId,
desc: row.desc,
id: row.id,
flag: 'view'
}
});
},
};
const openUrl = (path, name) => {
// window.open(path)
// downloadFile(path, name);
if(path.indexOf(".pdf") != -1 || path.indexOf(".png") != -1 || path.indexOf(".jpg") != -1 || path.indexOf(".jpeg") != -1){
window.open(path); // 跳转链接
}else{
if (!path) return ElMessage.error('文件地址不存在!');
downloadFile(path, name);
}
};
// 生命周期
return {
...toRefs(state),
...funMethods,
openUrl
};
}
});
</script>
逻辑2-抽离写法
<script lang='ts'>
import { defineComponent, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { downloadFile } from '@/axios';
import useDownFileMethods from '@/views/PersonalCenter/MyProcess/hooks/useDownFileMethods'
export default defineComponent({
name: 'leaveCom',
props: [
'state',
'name'
],
components: { },
setup(props) {
//定义方法
//const openFile =useDownFileMethods(props).openFile
//或
const {
openFile
} =useDownFileMethods(props)
return {
openFile,
...toRefs(props.state),
};
}
});
</script>
附:
const { obj } = this.props
写法含义
等价于, const obj = this.props.obj
;
这是遵循ES6的语法的简写形式
公共方法
useDownFileMethods.ts
/*流程查看详情 公共方法*/
import {ElMessage} from "element-plus";
import {downloadFile} from "@/axios";
import {reactive} from "vue";
function useDownFileMethods(props) {
const tableData = reactive([
...(props.state?.staffInvoiceInfoDtoList || [])
]);
const openFile = (file, fileName) => {
//if (!file) return ElMessage.warning('文件地址不存在!');
//downloadFile(file, fileName);
if(file.indexOf(".pdf") != -1 || file.indexOf(".png") != -1 || file.indexOf(".jpg") != -1 || file.indexOf(".jpeg") != -1){
window.open(file); // 跳转链接
}else{
if (!file) return ElMessage.error('文件地址不存在!');
downloadFile(file, fileName);
}
}
const formatterTimesign = (timeSign) => {
return {0: '全天', 1: '上午', 2: '下午'}[timeSign];
}
return {
openFile,
formatterTimesign,
tableData
}
}
export default useDownFileMethods
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);
});
};