
File相关
File相关
File 对象继承自 Blob 对象
1 2
| <input type='file' id="fileItem"/> var file = document.getElementById('fileItem').files[0];
|
文件下载fetch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <a href="result.png" download>download</a> <a href="test.png" download="joker.png">下载</a>
function downloadFile(url, filename='') { fetch(url, { headers: new Headers({ Origin: location.origin, }), mode: 'cors', }) .then(res => res.blob()) .then(blob => { const blobUrl = window.URL.createObjectURL(blob) download(blobUrl, filename) window.URL.revokeObjectURL(blobUrl) }) } function download(href, filename = '') { const a = document.createElement('a') a.download = filename a.href = href document.body.appendChild(a) a.click() a.remove() }
|
文件下载axios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| function downloadExcel(endpoint, filename) { axios.get(endpoint, { responseType: 'blob' }) .then((response) => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', filename); link.style.display = 'none';
document.body.appendChild(link); link.click();
window.URL.revokeObjectURL(url); document.body.removeChild(link); }) .catch((error) => { console.error("Error downloading Excel file:", error); alert('An error occurred while downloading the Excel file. Please try again later.'); }); }
downloadExcel('/path/to/your/excel/endpoint', 'filename.xlsx');
|
在JavaScript中,new Blob([response.data]) 是用来创建一个新的 Blob 对象的语法。Blob 对象表示一段不可变的原始数据,它可以是任何类型的数据,通常用于处理文件和二进制数据。
在这个特定的上下文中,response.data 是Axios从HTTP响应中接收到的数据。当Axios请求的 responseType 被设置为 'blob' 时,response.data 将包含一个 Blob 对象,这个对象包含了响应主体中的二进制数据。
然而,有时候后端服务器可能直接发送二进制数据,而前端Axios在接收到这些数据时,即使设置了 responseType: 'blob',response.data 也已经是二进制数据了。在这种情况下,直接将这些数据包装在一个新的 Blob 对象中可能是必要的,以确保数据以正确的格式被处理。
通常,如果你已经设置了Axios的 responseType 为 'blob',并且服务器正确响应了二进制数据,那么你不需要再次创建一个新的 Blob 对象。你可以直接将 response.data 用作 Blob 对象
保存文本txt
1 2 3 4 5 6 7 8 9 10 11
| const downloadText = (text, filename = '') { const a = document.createElement('a') a.download = filename const blob = new Blob([text], {type: 'text/plain'}) a.href = window.URL.createObjectURL(blob) document.body.appendChild(a) a.click() a.remove() }
|
1 2 3 4 5 6 7 8 9 10 11
| const clickEvent = new MouseEvent('click', { view: window, bubbles: true, cancelable: false, clientX: 100, clientY: 100, ctrlKey: true, shiftKey: false });
element.dispatchEvent(clickEvent);
|