前端如何实现文件的下载

async function downloadFileFromAPI(url, filename) {

try {

const response = await fetch(url);

if (!response.ok) {

throw new Error('Network response was not ok');

}

const blob = await response.blob();

const downloadUrl = URL.createObjectURL(blob);

const a = document.createElement('a');

a.href = downloadUrl;

a.download = filename;

document.body.appendChild(a);

a.click();

document.body.removeChild(a);

URL.revokeObjectURL(downloadUrl);

} catch (error) {

console.error('There has been a problem with your fetch operation:', error);

}

}

// 调用示例

downloadFileFromAPI('https://example.com/file.txt', 'downloaded_file.txt');