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 |
toDataURL = (url, callback) => { const xhr = new XMLHttpRequest(); xhr.onload = function () { const reader = new FileReader(); reader.onloadend = function () { callback(reader.result.replace(/^data:image\/\w+;base64,/, '')); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.responseType = 'blob'; xhr.send(); } downloadImage = (file) => { const { name, url, file_type } = file; const fileType = file_type.split('/')[1]; const link = document.createElement('a'); link.style = 'position: fixed; left -10000px;'; link.download = /\.\w+/.test(name) ? name : `${name}.${fileType}`; this.toDataURL(url, function (dataUrl) { link.href = `data:application/octet-stream;base64,${dataUrl}`; document.body.appendChild(link); link.click(); document.body.removeChild(link); }); }; handleDownloadButton = (file) => { const imageTypes = ['bmp', 'ico', 'mp3', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'svg']; const { name, file_type, url } = file; const fileType = file_type.split('/')[1]; const isSafari = navigator.userAgent.indexOf('Safari') !== -1; if (isSafari && (imageTypes.includes(fileType))) { this.downloadImage(file); } else { const link = document.createElement('a'); link.download = name; link.href = url; link.click(); } }; |
1 2 3 4 5 6 7 8 |
const file = ... ... <span className={'react-grid-Cell-download'} style={editIcon} key={`downloadFile${id}`} onClick={() => this.handleDownloadButton(file)} > |