Open wzhanjun opened 4 years ago
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // the filename you want a.download = 'todo-1.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('your file has downloaded!'); // or you know, something with better UX... }) .catch(() => alert('oh no!'));
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <button onclick="GetFile()">下载</button> <script> // 会先下载流,完成后才弹出选择目录,所以最好加上进度条 function GetFile(){ axios({ url: `http://image.wangrui8.top/dms-2019-07-22-00-00~1.mp4`, method: 'get', responseType: 'blob', onDownloadProgress (progress){ // 这里是下载的进度 console.log(Math.round(progress.loaded / progress.total * 100) + '%'); }, }) .then(res=>{ let blobUrl = window.URL.createObjectURL(res.data); let link = document.createElement('a'); document.body.appendChild(link); link.href = blobUrl; link.download = '下载文件.mp4'; link.click(); window.URL.revokeObjectURL(blobUrl); }) } </script> </body> </html>
参考: https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery https://my.oschina.net/u/4342183/blog/3419827
参考: https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery https://my.oschina.net/u/4342183/blog/3419827