下载功能调试

This commit is contained in:
BianLzhaoMin 2025-03-18 09:52:43 +08:00
parent 0091f5c9e7
commit a85a08703b
2 changed files with 111 additions and 76 deletions

View File

@ -1,79 +1,118 @@
import { get, post, put } from '@/http/index.ts'; import { get, post, put } from '@/http/index.ts'
import axios from 'axios'
import { saveAs } from 'file-saver'
const baseUrl = import.meta.env.VITE_API_URL
const service = axios.create({
baseURL: baseUrl,
timeout: 60000,
})
// 下载blob文件 // 下载blob文件
export const downloadFile = ({ fileData, fileType, fileName }) => { export const downloadFile = ({ fileData, fileType, fileName }) => {
const blob = new Blob([fileData], { const blob = new Blob([fileData], {
type: fileType type: fileType,
}); })
const link = document.createElement('a'); const link = document.createElement('a')
link.href = URL.createObjectURL(blob); link.href = URL.createObjectURL(blob)
link.download = fileName; link.download = fileName
link.style.display = 'none'; link.style.display = 'none'
document.body.appendChild(link); document.body.appendChild(link)
link.click(); link.click()
URL.revokeObjectURL(link.href); URL.revokeObjectURL(link.href)
document.body.removeChild(link); document.body.removeChild(link)
}; }
// 通用a链接下载 // 通用a链接下载
export const downloadFileByUrl = (url) => { export const downloadFileByUrl = (url) => {
const link = document.createElement('a'); const link = document.createElement('a')
link.href = url; // 设置文件 URL link.href = url // 设置文件 URL
link.download = ''; // 提供下载提示 link.download = '' // 提供下载提示
document.body.appendChild(link); // 将链接添加到 DOM document.body.appendChild(link) // 将链接添加到 DOM
link.click(); // 模拟点击下载 link.click() // 模拟点击下载
document.body.removeChild(link); // 下载后移除链接 document.body.removeChild(link) // 下载后移除链接
}; }
// pdf、doc、docx等文件下载 // pdf、doc、docx等文件下载
export const downloadFileData = ({ fileName, fileUrl }) => { export const downloadFileData = ({ fileName, fileUrl }) => {
const link = document.createElement('a'); const link = document.createElement('a')
link.setAttribute('download', ''); link.setAttribute('download', '')
link.style.display = 'none'; link.style.display = 'none'
link.href = fileUrl; link.href = fileUrl
link.download = fileName; link.download = fileName
document.body.appendChild(link); document.body.appendChild(link)
link.click(); link.click()
// URL.revokeObjectURL(link.href) // URL.revokeObjectURL(link.href)
document.body.removeChild(link); document.body.removeChild(link)
}; }
const blobValidate = (data) => {
return data.type !== 'application/json'
}
const tansParams = (params) => {
let result = ''
for (const propName of Object.keys(params)) {
const value = params[propName]
var part = encodeURIComponent(propName) + '='
if (value !== null && value !== '' && typeof value !== 'undefined') {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (
value[key] !== null &&
value[key] !== '' &&
typeof value[key] !== 'undefined'
) {
let params = propName + '[' + key + ']'
var subPart = encodeURIComponent(params) + '='
result += subPart + encodeURIComponent(value[key]) + '&'
}
}
} else {
result += part + encodeURIComponent(value) + '&'
}
}
}
return result
}
export function download(url, params, filename, config) { export function download(url, params, filename, config) {
console.log('🚀 ~ download ~ url:', url) console.log('🚀 ~ download ~ url:', url)
// downloadLoadingInstance = Loading.service({ // downloadLoadingInstance = Loading.service({
// text: '正在下载数据,请稍候', // text: '正在下载数据,请稍候',
// spinner: 'el-icon-loading', // spinner: 'el-icon-loading',
// background: 'rgba(0, 0, 0, 0.7)', // background: 'rgba(0, 0, 0, 0.7)',
// }); // });
return post(url, params, { return service
transformRequest: [ .post(url, params, {
(params) => { transformRequest: [
return tansParams(params); (params) => {
}, return tansParams(params)
], },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, ],
responseType: 'blob', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
...config, responseType: 'blob',
}) ...config,
.then(async (data) => { })
console.log('🚀 ~ .then ~ data:', data) .then(async (data) => {
const isBlob = blobValidate(data); console.log('🚀 ~ .then ~ data:', data)
console.log('🚀 ~ .then ~ isBlob:', isBlob) const isBlob = blobValidate(data)
if (isBlob) { console.log('🚀 ~ .then ~ isBlob:', isBlob)
const blob = new Blob([data]); if (isBlob) {
saveAs(blob, filename); const blob = new Blob([data])
} else { saveAs(blob, filename)
// const resText = await data.text(); } else {
// const rspObj = JSON.parse(resText); // const resText = await data.text();
// const errMsg = // const rspObj = JSON.parse(resText);
// errorCode[rspObj.code] || rspObj.msg || errorCode['default']; // const errMsg =
// Message.error(errMsg); // errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
} // Message.error(errMsg);
// downloadLoadingInstance.close(); }
}) // downloadLoadingInstance.close();
.catch((r) => { })
console.error(r); .catch((r) => {
// Message.error('下载文件出现错误,请联系管理员!'); console.error(r)
// downloadLoadingInstance.close(); // Message.error('下载文件出现错误,请联系管理员!');
}); // downloadLoadingInstance.close();
} })
}

View File

@ -1050,9 +1050,9 @@ const onTempDownLoad = () => {
cancelButtonText: '取消', cancelButtonText: '取消',
type: 'warning', type: 'warning',
}) })
.then(async() => { .then(async () => {
const res: any = await downLoadTemplate() // const res: any = await downLoadTemplate()
const blob = res.blob() // const blob = res.blob()
// downloadFile({ // downloadFile({
// fileData: res, // fileData: res,
// fileType: 'application/octet-stream', // fileType: 'application/octet-stream',
@ -1066,11 +1066,7 @@ const onTempDownLoad = () => {
// fileName: `_${new Date().getTime()}.xlsx`, // fileName: `_${new Date().getTime()}.xlsx`,
// }) // })
// }) // })
download( download('/material-mall/dev/downLoadDev', {}, `模版_${new Date().getTime()}.xlsx`)
'/material-mall/dev/downLoadDev',
{},
`模版_${new Date().getTime()}.xlsx`
)
}) })
.catch(() => {}) .catch(() => {})
} }