ที่นี้มาถึงการที่ใช้ fetch download file จาก server ซึ่งวิธีนี้ง่ายกว่าการใช้ jQuery ดึงไฟล์มามาก จากที่เคยเขียน jQuery ajax download file เอาไว้จะเห็นว่าวิธีนี้ง่ายกว่ามาก
เริ่มจากการที่โหลด download.js มาก่อน โดยใช้คำสั่ง npm i downloadjs
ไฟล์กลางที่ไว้ใช้ร่วมกัน
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | scripts.js /* pitt phunsanit default fetch api options version 1 */ let fetchOptions = { "headers": { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, "method": "post" }; /* pitt phunsanit get file name from fetch api version 1 */ function fetchGetFilename(response) { let filename = ''; let disposition = response.headers.get('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; let matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { filename = matches[1].replace(/['"]/g, ''); } } return filename; } /* pitt phunsanit get status from fetch api version 1 */ function fetchStatus(Response) { if (Response.status >= 200 && Response.status < 300) { return Promise.resolve(Response); } else { return Promise.reject(new Error(Response.status + ' : ' + Response.statusText)); } } |
ตัวอย่างการใช้ fetch download file โดยใช้ downloadjs ช่วยให้ทำงานได้ทุกบราวเซอร์ (ยกเว้น IE ถ้าจะใช้กลับไปอ่าน Fetch API)
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 29 30 31 32 33 | JavaScript/fetch.download.html <!DOCTYPE html> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="author" content="Pitt Phunsanit"> <title>fetch: download</title> </head> <body> <script src="../node_modules/downloadjs/download.min.js"></script> <script src="../scripts.js"></script> <script> fetchOptions.body = 'file=ISO 3166-1 two aplha COUNTRY codes (01102009).xls&token=HH89VOiirgXlCdEqDrFs'; fetch('http://localhost/snippets/PHP/download.php', fetchOptions) .then(fetchStatus) .then( function(response) { if (response.ok) { let fileName = fetchGetFilename(response); let mimeType = response.headers.get('Content-Type'); response.blob().then(function(blob) { download(blob, fileName, mimeType); }); } } ) .catch(function(error) { alert(error); }); </script> </body></html> |
อ่านเพิ่มเติม