fileToBase64,base64ToFile
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="file" id="fileInput"> <script> document.getElementById('fileInput').addEventListener('change', function (e) { let file = e.target.files[0]; console.log(file) let fileName = file.name // 判断file是否图片,不超过2M,然后转为base64 if (!isImage(file)) { console.error('不是图片文件'); return; } if (file.size > 2 * 1024 * 1024) { // 如果文件大小超过2MB,输出错误信息并返回 console.error('文件过大'); return; } try { // 将文件转换为base64编码 convertToBase64(file).then(res => { console.log('转换后的base64数据:', res); let objFile = base64ToFile(res, fileName) console.log('转换后的文件数据:',objFile) }) } catch (err) { console.error('转换失败:', err); } }); function isImage(file) { const fileType = file.type; return fileType && fileType.startsWith('image/'); } function convertToBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = (e) => { const base64Data = e.target.result; resolve(base64Data); }; reader.onerror = (err) => { reject(err); }; reader.readAsDataURL(file); }); } function base64ToFile(base64, fileName) { let arr = base64.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], fileName, {type: mime}) } </script> </body> </html>