亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

前端 javascript 實現文件下載的示例

瀏覽:90日期:2023-10-07 11:54:27

在 html5 中,a 標簽新增了 download 屬性,包含該屬性的鏈接被點擊時,瀏覽器會以下載文件方式下載 href 屬性上的鏈接。示例:

<a rel='external nofollow' download='baidu.html'>下載</a>

1. 前端 js 下載實現與示例

通過 javascript 動態創建一個包含 download 屬性的 a 元素,再觸發點擊事件,即可實現前端下載。

代碼示例:

function download(href, title) { const a = document.createElement(’a’); a.setAttribute(’href’, href); a.setAttribute(’download’, title); a.click();}

說明:

href 屬性設置要下載的文件地址。這個地址支持多種方式的格式,因此可以實現豐富的下載方法。 download 屬性設置了下載文件的名稱。但 href 屬性為普通鏈接并且跨域時,該屬性值設置多數情況下會被瀏覽器忽略。

1.1 普通連接下載示例

// 下載圖片download(’https://lzw.me/images/gravatar.gif’, ’lzwme-gravatar’);// 下載一個連接download(’https://lzw.me’, ’lzwme-index.html’);

1.2 href 為 data URIs 示例data URI 是前綴為 data:scheme 的 URL,允許內容創建者在文檔中嵌入小文件。數據URI由四個部分組成:前綴(數據:),指示數據類型的MIME類型,如果非文本則為可選的base64令牌,數據本身:

data:[<mediatype>][;base64],<data>

鏈接的 href 屬性為 data URIs 時,也可以實現文件內容的下載。示例:

download(’data:,Hello%2C%20World!’, ’data-uris.txt’);download(’data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D’, ’data-uris.txt’);

1.3 canvas 下載示例對于 canvas 可以通過 toDataURL 方法取得 data URIs 格式的內容。

1.4 二進制內容下載URL.createObjectURL 方法會根據傳入的參數創建一個指向該參數對象的 URL。新的對象 URL 指向執行的 File 對象或者是 Blob 對象。

URL.createObjectURL 的參數是 File 對象或者 Blob 對象,File 對象也就是通過 input[type=file] 選擇的文件,Blob 對象是二進制數據。

將URL.createObjectURL 返回值設為 href 屬性的值,即可實現二進制內容下載。示例:

const content = ’Welcome to lzw.me!’;const blob = new Blob([content]);const href = URL.createObjectURL(blob);download(href, ’download-text.txt’);URL.revokeObjectURL(href);

1.5 前端下載方法示例綜合上述討論,這里給出一個前端實現下載的 saveAs 方法的 TypeScript 示例:

/** * 通過創建 a dom 對象方式實現前端文件下載 * @param href 要下載的內容鏈接。當定義了 toBlob 時,可以為純文本或二進制數據(取決于 toBlob 格式 * @param fileName 下載后的文件名稱 * @param toBlob 如設置該參數,則通過 blob 方式將 href 轉換為要保存的文件內容,該參數將入參為 new Blob([href], toBlob) 的第二個參數 * @example * ```js * saveAs(’abc’, ’abc.txt’, {}); * saveAs(’data:,Hello%2C%20World!’, ’hello.txt’); * saveAs(’https://lzw.me/images/avatar/lzwme-80x80.png’, ’lzwme-logo.png’); * ``` */export function saveAs(href: string | Blob, fileName?: string, toBlob?: PlainObject) { const isBlob = href instanceof Blob || toBlob; if (!fileName && typeof href === ’string’ && href.startsWith(’http’)) { fileName = href.slice(href.lastIndexOf(’/’) + 1); } fileName = decodeURIComponent(fileName || ’download’); if (typeof href === ’string’ && toBlob) href = new Blob([href], toBlob); if (href instanceof Blob) href = URL.createObjectURL(href); const aLink = document.createElement(’a’); aLink.setAttribute(’href’, href); aLink.setAttribute(’download’, fileName); aLink.click(); // const evt = document.createEvent('HTMLEvents'); // evt.initEvent('click', false, false); // aLink.dispatchEvent(evt); if (isBlob) setTimeout(() => URL.revokeObjectURL(aLink.href), 100); return aLink;}

2.檢測瀏覽器是否支持 download 屬性

download 屬性為 html5 新增內容,瀏覽器支持情況可參考:http://caniuse.com/#feat=download

<img src='https://lzw.me/wp-content/uploads/2017/04/a-download.png' alt='' />

判斷瀏覽器是否支持該屬性,只需要檢測 a 標簽是否存在 download 屬性。示例:

const downloadAble = ’download’ in document.createElement(’a’);

對于不支持的瀏覽器,只能另想他法或者予以降級處理了。

3.使用 serviceWorker 和 fetch API 代理實現

前端下載更多的需求是因為內容產生于前端。那么可以在后端實現一個這樣的 API ,它在接收到前端發出的內容后返回下載格式的數據。這種實現就不存在瀏覽器兼容問題。

利用 serviceWorker 和 fetch API 截攔瀏覽器請求,只需實現好約定邏輯,也可實現這種功能需求。示例:

在頁面中,通過 fetch API 構造請求:

fetch(’lzwme.txt’, { isDownload: true, body: {data: new Blob(’hi!’) }})

在 serviceWorker 中,截攔附帶 isDownload 頭信息的請求,構造下載回應:

self.addEventListener(’fetch’, function(event) { const req = event.request; if (!req.headers.get(’isDownload’)) {retrun fetch(req); } const filename = encodeURIComponent(req.url); const contentType = req.headers.get(’Content-Type’) || ’application/force-download’; const disposition = 'inline;filename=' + filename + ';filename*=utf-8’’' + filename const myBody = req.headers.get(body).data; event.respondWith(new Response(myBody, { headers: {’Content-Type’: contentType,’Content-Disposition’: disposition }}) );});

4 使用 ajax (xhr與fetch API) 方式下載服務器文件

以上主要討論的是純前端實現下載保存文件的方法。對于下載服務器文件,最簡的方式就是 window.open(url) 和 location.href=url 了,但是其的弊端也很明顯,當出錯時整個頁面都會掛掉,而且也無法獲得下載狀態與進度,下載時間稍長時體驗相當不好。

下面介紹一下使用 xhr 和 fetch API 實現文件下載的方法。其主要思路為:將請求結果設為 Blob 類型,然后采用前端下載保存 Blob 類型數據的方式實現下載。

4.1 使用 xhr 下載遠程服務器文件代碼示例:

/** 前端下載/保存文件 */function saveAs(href, fileName) { const isBlob = href instanceof Blob; const aLink = document.createElement(’a’); aLink.href = isBlob ? window.URL.createObjectURL(href) : href; aLink.download = fileName; aLink.click(); if (isBlob) setTimeout(() => URL.revokeObjectURL(aLink.href), 100);}function xhrDownload(url, options = {}) { options = Object.assign({ method: ’get’, headers: {} }, options); return new Promise((reslove, reject) => { const xhr = new XMLHttpRequest(); xhr.responseType = ’blob’; // options.responseType; if (options.headers) { for (const key in options.headers) xhr.setRequestHeader(key, options.headers[key]); } xhr.onload = () => { // 從 Content-Disposition 中獲取文件名示例 const cd = xhr.getResponseHeader(’Content-Disposition’); if (cd && cd.includes(’fileName’) && !options.fileName) options.fileName = cd.split(’fileName=’)[1]; options.fileName = decodeURIComponent(options.fileName || ’download-file’); if (+xhr.status == 200) {saveAs(xhr.response, options.fileName);reslove(options.fileName);

使用 fecth API 下載遠程服務器文件

function fetchDownload(url, options = {}) { options = Object.assign({ credentials: ’include’, method: ’get’, headers: {} }, options); return fetch(url, options).then(response => { return response.blob().then(blob => { if (!blob || !blob.size) return Promise.reject(’empty’); // 從 Content-Disposition 中獲取文件名示例 const cd = response.headers.get(’Content-Disposition’); if (cd && cd.includes(’fileName’) && !options.fileName) options.fileName = cd.split(’fileName=’)[1]; options.fileName = decodeURIComponent(options.fileName || ’download-file’); saveAs(blob, options.fileName); return options.fileName; }); });}// 測試fetchDownload(’https://lzw.me/images/avatar/lzwme-80x80.png’, { // method: ’post’, // headers: { // ’Content-Type’: ’application/json’ // }, // body: JSON.stringify({ // pageSize: 100000, // startPage: 0 // }) })

以上就是前端 javascript 實現文件下載的示例的詳細內容,更多關于JavaScript 文件下載的資料請關注好吧啦網其它相關文章!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 玛雅视频网站在线观看免费 | 日韩一级片视频 | 中文字幕一精品亚洲无线一区 | 亚洲精品女同一区二区三区 | 一级做性色a爰片久久毛片免费 | 特黄特色一级特色大片中文 | 国内精品视频 在线播放 | 国产精品成人久久久 | 免费黄色在线网址 | 香蕉九九 | 国产福利视频在线观看 | 久99久热只有精品国产99 | 日本中文字幕不卡在线一区二区 | 国产精品白丝喷水在线观看 | 国产日韩第一页 | 国产成人91青青草原精品 | 色一情一伦一区二区三 | 美国aaaa一级毛片啊 | 成人啪| 婷婷久久综合九色综合98 | 日本高清xxxx免费视频 | 国产短视频精品区第一页 | 国产在线精品99一卡2卡 | 青青青国产依人精品视频 | 一级待一黄aaa大片在线还看 | 香蕉人精品视频多人免费永久视频 | 中文字幕35 | 国产在线激情 | 免费日韩在线 | 免费看精品黄线在线观看 | 欧美日韩精品一区二区三区不卡 | 天干天干夜天干天天爽 | 入逼视频| 国产一国产一级毛片视频 | 亚洲精品日韩中文字幕久久久 | 久久久精品午夜免费不卡 | 在线综合网 | 欧美一级毛片特黄黄 | 成人在线免费网站 | 久久精品免费全国观看国产 | 2022日本卡一卡二新区 |