print.js
3.07 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import config from '@/config'
import { getToken } from '@/utils/auth.js'
export async function printFile(id, fileName = '合同.pdf') {
const bizId = id != null ? String(id) : ''
if (!bizId) {
uni.showToast({ title: '未获取到合同ID', icon: 'none' })
return
}
uni.showLoading({ title: '下载中' })
try {
const baseUrl = (config && config.baseUrl) ? String(config.baseUrl).replace(/\/$/, '') : ''
const rawUrl = `${baseUrl}/contract/contractDistributorStandard/printStandardContract?id=${encodeURIComponent(bizId)}`
const token = getToken()
const header = {}
if (token) header['X-Auth-Token'] = token
let url = rawUrl
// #ifdef H5
if (token) {
const separator = url.includes('?') ? '&' : '?'
url = `${url}${separator}X-Auth-Token=${encodeURIComponent(token)}`
}
// #endif
const res = await new Promise((resolve, reject) => {
uni.downloadFile({
url,
header,
success: resolve,
fail: reject
})
})
if (!(res && res.statusCode === 200)) {
uni.showToast({ title: '下载失败', icon: 'none' })
return
}
const filePath = res.tempFilePath
// #ifdef H5
const ua = navigator.userAgent.toLowerCase()
const isAndroid = ua.indexOf('android') > -1 || ua.indexOf('adr') > -1
const isWeChat = ua.indexOf('micromessenger') !== -1
if (isWeChat && isAndroid) {
uni.showModal({
title: '提示',
content: '微信环境下不支持直接打开,请复制链接后在浏览器打开',
confirmText: '复制链接',
showCancel: false,
success: function (r) {
if (r.confirm) {
uni.setClipboardData({
data: url,
success: function () { uni.showToast({ title: '链接已复制', icon: 'success' }) }
})
}
}
})
} else {
const win = window.open(filePath, '_blank')
if (!win) {
const link = document.createElement('a')
link.href = filePath
link.download = fileName || 'download'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
// #endif
// #ifndef H5
const ext = fileName && String(fileName).includes('.') ? String(fileName).split('.').pop().toLowerCase() : 'pdf'
uni.openDocument({
filePath,
fileType: ext || 'pdf',
showMenu: true,
fail: function () {
uni.showToast({ title: '无法打开此文件', icon: 'none' })
}
})
// #endif
} catch (e) {
uni.showToast({ title: '下载出错', icon: 'none' })
} finally {
uni.hideLoading()
}
}