在JavaScript中实现附件下载,通常可以通过创建一个隐藏的<a>
标签,并模拟点击该标签来触发下载。以下是几种常见的方法:
<a>
标签和download
属性function downloadFile(filename, content) {
// 创建一个Blob对象,content可以是字符串、数组缓冲区等
const blob = new Blob([content], { type: 'application/octet-stream' });
// 创建一个a标签
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
// 将a标签添加到DOM中并模拟点击
document.body.appendChild(link);
link.click();
// 移除a标签并释放URL对象
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
}
// 使用示例
downloadFile('example.txt', 'Hello, world!');
fetch
API和Blob
async function downloadFile(url, filename) {
const response = await fetch(url);
const blob = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
}
// 使用示例
downloadFile('https://example.com/file.pdf', 'downloaded.pdf');
function downloadBase64File(filename, base64Data, mimeType) {
const byteCharacters = atob(base64Data.split(',')[1]);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: mimeType });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
}
// 使用示例
const base64Data = 'data:text/plain;base64,SGVsbG8sIHdvcmxkIQ=='; // "Hello, world!"的Base64编码
downloadBase64File('example.txt', base64Data, 'text/plain');
<a>
标签,可以很容易地实现文件下载。download
属性。download
属性,但一些旧版本的浏览器可能不支持。可以通过检测浏览器特性来提供降级方案。通过以上方法,你可以在JavaScript中实现附件下载功能,并根据具体需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云