通用下载方法

通用下载方法
/** * 通用下载方法 * @param {string} url - 下载地址 * @param {object} params - 请求参数(POST时作为请求体,GET时作为查询参数) * @param {string} filename - 下载文件名(可选,不传时从响应头Content-Disposition自动提取) * @param {object} config - 请求配置(可选,可传入 method 指定请求方式,默认 post) * @param {boolean} showLoading - 是否显示加载动画(默认 true) * @returns {Promise} - 返回 Promise */ export function download(url, params, filename, config, showLoading = true) { // 显示下载加载动画 if (showLoading) { downloadLoadingInstance = ElLoading.service({ text: "正在下载数据,请稍候", background: "rgba(0, 0, 0, 0.7)" }) } // 从配置中获取请求方式,默认为 POST const method = (config && config.method) || 'post' // 构建请求配置,强制设置 responseType 为 blob 用于文件下载 const requestConfig = { responseType: 'blob', ...config } // 删除 method 属性,避免传递给 axios delete requestConfig.method let requestPromise // 根据请求方式选择 GET 或 POST if (method === 'get') { // GET 请求:参数通过 params 传递(查询参数) requestConfig.params = params requestPromise = service.get(url, requestConfig) } else { // POST 请求:参数作为请求体,使用表单编码 requestPromise = service.post(url, params, { transformRequest: [(params) => { return tansParams(params) }], headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, ...requestConfig }) } return requestPromise.then(async (response) => { // 响应格式为 { data: blobData, headers: responseHeaders } const blobData = response.data const headers = response.headers // 验证响应是否为 Blob 类型 const isBlob = blobValidate(blobData) if (isBlob) { // 将响应数据转为 Blob 对象 const blob = new Blob([blobData]) // 确定最终文件名:优先使用传入的 filename,否则从响应头提取 let finalFilename = filename if (!finalFilename && headers && headers['content-disposition']) { // 解析 Content-Disposition 响应头获取文件名 const disposition = headers['content-disposition'] const match = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/) if (match && match[1]) { finalFilename = decodeURIComponent(match[1].replace(/['"]/g, '')) } } // 使用 file-saver 保存文件 saveAs(blob, finalFilename) } else { // 如果不是 Blob,说明是错误响应,解析错误信息 const resText = await blobData.text() const rspObj = JSON.parse(resText) const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'] ElMessage.error(errMsg) } // 关闭加载动画 if (showLoading && downloadLoadingInstance) { downloadLoadingInstance.close() } }).catch((r) => { // 捕获下载异常 console.error(r) ElMessage.error('下载文件出现错误,请联系管理员!') // 关闭加载动画 if (showLoading && downloadLoadingInstance) { downloadLoadingInstance.close() } }) }

用法

const url = `/annotation/model/config/download?modelKey=${model.modelKey}`; download(url, {}, undefined, { method: 'get' }, false).then(() => { proxy.$modal.msgSuccess("下载配置文件成功"); });