如何将图片预览的DataURL通过HTML表单POST提交至PHP后端
解决方案:将图片DataURL通过POST提交到PHP后端
要实现把图片的DataURL而非文件名提交到后端,你需要通过隐藏表单字段存储DataURL,再随表单一起提交,具体修改如下:
1. 修改HTML表单
在表单内添加一个隐藏的input字段,用来存储生成的DataURL:
<form action="/inc/sendtochan.php" method="post"> <label for="fname">Title:</label><br> <input type="text" id="fname" name="title" value="" size="64"><br> <label for="discription">Enter content description:</label><br> <textarea name="discription" rows="10" cols="60"></textarea><br> <label for="link">Link to content:</label><br> <input type="text" id="lcontent" name="lcontent" value="" size="64"><br> <label for="link">Select Image:</label><br> <div class="profile-picture"> <h1 class="upload-icon"> <i class="fa fa-plus fa-2x" aria-hidden="true"></i> </h1> <input class="file-uploader" type="file" onchange="upload()" accept="image/*" name="imageurl" /> </div><br><br> <!-- 添加隐藏字段存储DataURL --> <input type="hidden" name="image_dataurl" id="image_dataurl"> <input type="submit" name="submitcontent" value="Send Content to Channel"> </form>
2. 更新JavaScript代码
在生成DataURL后,将其赋值给刚才添加的隐藏字段,确保表单提交时能携带该数据:
function upload() { const fileUploadInput = document.querySelector('.file-uploader'); if (!fileUploadInput.value) { return; } const image = fileUploadInput.files[0]; if (!image.type.includes('image')) { return alert('Sorry Only images are allowed!'); } if (image.size > 10_000_000) { return alert('Maximum upload size is 10MB!'); } const fileReader = new FileReader(); fileReader.readAsDataURL(image); fileReader.onload = (fileReaderEvent) => { const profilePicture = document.querySelector('.profile-picture'); profilePicture.style.backgroundImage = `url(${fileReaderEvent.target.result})`; // 将DataURL存入隐藏字段 document.getElementById('image_dataurl').value = fileReaderEvent.target.result; } }
3. 修改后端PHP代码
现在后端可以通过$_POST['image_dataurl']获取到完整的DataURL,你可以对其进行解析并保存为图片文件:
<?php // 获取DataURL $imageDataURL = trim($_POST['image_dataurl']); // 解析DataURL,提取图片内容和格式 list($type, $data) = explode(';', $imageDataURL); list(, $data) = explode(',', $data); $imageContent = base64_decode($data); // 获取图片扩展名 preg_match('/^data:image\/(\w+);base64/', $imageDataURL, $matches); $extension = $matches[1]; // 生成保存的文件名(可根据需求调整) $fileName = uniqid() . '.' . $extension; $savePath = './uploads/' . $fileName; // 确保uploads目录存在且有写入权限 // 保存图片到服务器 if (file_put_contents($savePath, $imageContent)) { echo "图片上传成功,路径:" . $savePath; } else { echo "图片保存失败"; } ?>
注意事项
- 确保服务器上的
uploads目录存在,并且PHP有写入权限 - DataURL会增加数据体积(比原文件大30%左右),如果上传大图片可能需要调整PHP的
post_max_size和upload_max_filesize配置
内容的提问来源于stack exchange,提问作者Nemzzy Builds
相关产品推荐
相关产品推荐

