当前位置: 首页> 汽车> 维修 > 雅布设计作品_成都娱乐场所最新消息_视频号关键词搜索排名_百度搜索排名怎么收费

雅布设计作品_成都娱乐场所最新消息_视频号关键词搜索排名_百度搜索排名怎么收费

时间:2025/7/12 23:45:38来源:https://blog.csdn.net/m0_74823434/article/details/144631185 浏览次数: 0次
雅布设计作品_成都娱乐场所最新消息_视频号关键词搜索排名_百度搜索排名怎么收费

前端文件下载有多种方法,每种方法适用于不同的场景。以下是几种常见的前端文件下载方法及其示例代码:

1. 直接设置 <a> 标签的 href 属性

适用于简单的文件下载,服务器会自动响应带有 Content-Disposition: attachment 头的文件。

function downloadFile(url, filename, token) {// 创建一个隐藏的 <a> 元素const a = document.createElement('a');a.style.display = 'none';// 检查 URL 是否已经包含查询参数const urlWithToken = url.includes('?') ? `${url}&token=${encodeURIComponent(token)}`: `${url}?token=${encodeURIComponent(token)}`;// 设置 <a> 元素的 href 属性为带有 token 的 URLa.href = urlWithToken;// 设置下载的文件名a.download = filename || 'download';// 将 <a> 元素添加到文档中document.body.appendChild(a);// 触发点击事件a.click();// 移除 <a> 元素document.body.removeChild(a);
}// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
2. 使用 fetch API 下载 Blob 文件

适用于需要处理文件内容的情况,例如从服务器获取文件内容后手动触发下载。

function downloadFile(url, filename, token) {fetch(url, {method: 'GET',headers: {'Authorization': `Bearer ${token}`,// 其他头部信息}}).then(response => {if (!response.ok) {throw new Error('Network response was not ok ' + response.statusText);}return response.blob();}).then(blob => {const url = window.URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = filename || 'download';a.style.display = 'none';document.body.appendChild(a);a.click();window.URL.revokeObjectURL(url);document.body.removeChild(a);}).catch(error => {console.error('Download failed:', error);});
}// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
3. 使用表单提交

适用于需要携带参数或进行 POST 请求的情况。

<form id="downloadForm" action="https://example.com/download" method="POST" target="_blank"><input type="hidden" name="token" value="yourTokenValue"><!-- 其他需要的输入字段 -->
</form><script>document.getElementById('downloadForm').submit();
</script>
4. 使用 iframe 触发下载

适用于不需要用户交互的文件下载。

<iframe id="downloadIframe" style="display:none;"></iframe><script>function triggerDownload(url) {const iframe = document.getElementById('downloadIframe');iframe.src = url;}// 调用函数triggerDownload('https://example.com/path/to/file.pdf');
</script>
5. 使用 XMLHttpRequest 下载 Blob 文件

适用于需要兼容旧浏览器的情况。

function downloadFile(url, filename, token) {const xhr = new XMLHttpRequest();xhr.open('GET', url, true);xhr.setRequestHeader('Authorization', `Bearer ${token}`);xhr.responseType = 'blob';xhr.onload = function() {if (this.status === 200) {const blob = this.response;const url = window.URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = filename || 'download';a.style.display = 'none';document.body.appendChild(a);a.click();window.URL.revokeObjectURL(url);document.body.removeChild(a);} else {console.error('Download failed:', this.statusText);}};xhr.onerror = function() {console.error('Download failed:', this.statusText);};xhr.send();
}// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
6. 使用 BlobFileSaver.js

FileSaver.js 是一个第三方库,可以简化文件下载操作。

首先,安装 FileSaver.js

npm install file-saver

然后在代码中使用:

import { saveAs } from 'file-saver';function downloadFile(url, filename, token) {fetch(url, {method: 'GET',headers: {'Authorization': `Bearer ${token}`, // 添加 token 到请求头// 其他头部信息}}).then(response => {if (!response.ok) {throw new Error('Network response was not ok ' + response.statusText);}return response.blob();}).then(blob => {saveAs(blob, filename || 'download');}).catch(error => {console.error('Download failed:', error);});
}// 调用函数
downloadFile('https://example.com/path/to/file.pdf', 'file.pdf', 'yourTokenValue');
总结
  • 直接设置 <a> 标签的 href 属性:适用于简单的文件下载。
  • 使用 fetch API 下载 Blob 文件:适用于需要处理文件内容的情况。
  • 使用表单提交:适用于需要携带参数或进行 POST 请求的情况。
  • 使用 iframe 触发下载:适用于不需要用户交互的文件下载。
  • 使用 XMLHttpRequest 下载 Blob 文件:适用于需要兼容旧浏览器的情况。
  • 使用 BlobFileSaver.js:适用于需要简化文件下载操作的情况。
关键字:雅布设计作品_成都娱乐场所最新消息_视频号关键词搜索排名_百度搜索排名怎么收费

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: