<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>图片到Base64 URL</title> <style> html, body { font-family: sans-serif; padding: 0; margin: 0; width: 100%; height: 100%; } body { display: flex; } .drop-zone { flex: 1; background: #E6E6E6; transition: background 50ms ease-in; display: flex; flex-direction: column; } .drop-zone p { text-align: center; } .drag-over .drop-zone { background: gold; } .error { color: red; } textarea { border: 0; background: none; display: block; padding: 0; margin: 0; font-family: monospace; flex: 1; } textarea:focus { outline: none; } .get-it { display: none; } .get-it a { flex: 1; text-align: center; padding: 0.5rem; } .success .get-it { display: flex; } </style></head><body> <div class="drop-zone"> <p>将您的图片拖放到此处以将其转换为Base64数据URL</p> <p class="error"></p> <div class="get-it"> <a id="copy" href="#copy">复制</a> <a id="download" download="base64.txt">下载</a> </div> <textarea></textarea> </div> <script> (() => { 'use strict'; const body = document.body; const dropZone = document.querySelector('.drop-zone'); const error = document.querySelector('.error'); const textarea = document.querySelector('textarea'); const download = document.querySelector('#download'); const copy = document.querySelector('#copy'); const MIME_TYPE = 'text/plain'; window.addEventListener('dragenter', e => { body.classList.add('drag-over'); e.preventDefault(); }, false); window.addEventListener('dragleave', e => { body.classList.remove('drag-over'); e.preventDefault(); }, false); dropZone.addEventListener('dragover', e => { e.preventDefault(); }); dropZone.addEventListener('drop', e => { e.preventDefault(); const dt = e.dataTransfer; const file = dt.items[0].getAsFile(); if (!/image/.test(file.type)) { return showError('File has to be an image file'); } const reader = new FileReader(); reader.addEventListener('load', () => { textarea.value = reader.result; const blob = new Blob([reader.result], {type: MIME_TYPE}); const href = window.URL.createObjectURL(blob); download.setAttribute('href', href); download.setAttribute('downloadUrl', [ MIME_TYPE, 'base64.txt', href, ].join(':')); body.classList.remove('drag-over'); body.classList.add('success'); }); reader.readAsDataURL(file); }); copy.addEventListener('click', (event)=> { event.preventDefault(); const range = document.createRange(); range.selectNode(textarea); window.getSelection().addRange(range); try { document.execCommand('copy'); } catch (error) { alert('Copy failed'); } }); function showError(message) { body.classList.remove('drag-over'); error.innerText = message; setTimeout(()=> { error.innerText = ''; }, 5000); } })(); </script></body></html>
本文地址:https://www.chenyajun.net/index.php/post/100.html
版权声明:本文为原创文章,版权归 chenyajun 所有,欢迎分享本文,转载请保留出处!
版权声明:本文为原创文章,版权归 chenyajun 所有,欢迎分享本文,转载请保留出处!