React传递Base64图片字符串至PHP后端保存到本地文件夹时的空值与0KB文件问题
Fixing FormData/Base64 Image Upload Issue Between React and PHP
Let's break down what's going wrong here and fix it step by step:
Key Issues Identified
- Frontend Backend Mismatch: You created a
FormDataobject in React but never used it to send the file. Instead, you converted the file to Base64 and sent a JSON payload withid,slotname, andslotimage—so your PHP code is looking forfilefields that don't exist. - Invalid URL Parameter Syntax: Your request URL uses two
?characters to separate parameters. Correct syntax uses&for additional parameters:- Wrong:
http://localhost/server/index.php?saveImageToFolder=true?id=1&name=fdsfsdf - Correct:
http://localhost/server/index.php?saveImageToFolder=true&id=1&name=fdsfsdf
- Wrong:
Solution 1: Use FormData for Direct File Upload (Recommended)
This is the more efficient approach (avoids Base64's 30% file size overhead) and aligns with standard file upload practices.
Updated React Code
const onChangeImage = (e, id, slotname) => { const fileFound = e.target.type === 'file' && e.target.files[0]; if (!fileFound) return; const formData = new FormData(); formData.append('file', fileFound); formData.append('id', id); formData.append('slotname', slotname); // Replace with your upload function (or use fetch directly) fetch('http://localhost/server/index.php?saveImageToFolder=true', { method: 'POST', body: formData }) .then(res => res.json()) .then(data => console.log('Upload success:', data)) .catch(err => console.error('Upload error:', err)); }
Updated PHP Code
header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Max-Age: 3600"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); include("connect.php"); error_reporting(E_ALL); // Enable error reporting for debugging session_start(); if(isset($_GET['saveImageToFolder'])){ // Check if file was uploaded successfully if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK){ $tempPath = $_FILES['file']['tmp_name']; $targetFileName = 'image.png'; // Customize this (e.g., use original filename or unique ID) $targetPath = __DIR__ . '/' . $targetFileName; // Move temporary file to permanent location if(move_uploaded_file($tempPath, $targetPath)){ echo json_encode(['success' => true, 'message' => 'Image saved successfully']); } else { echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file (check directory permissions)']); } } else { $errorMsg = $_FILES['file']['error'] ?? 'No file uploaded or upload failed'; echo json_encode(['success' => false, 'message' => 'Upload error: ' . $errorMsg]); } }
Solution 2: Continue Using Base64 Upload (For Small Files Only)
If you need to stick with Base64, adjust your PHP code to look for the correct payload field, and ensure your frontend sends data properly.
Updated PHP Code
header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Max-Age: 3600"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); include("connect.php"); error_reporting(E_ALL); session_start(); // Parse JSON payload (since React sends JSON, not form-encoded data) $postData = json_decode(file_get_contents('php://input'), true); if($postData) $_POST = $postData; if(isset($_GET['saveImageToFolder'])){ if(isset($_POST['slotimage'])){ $base64Data = $_POST['slotimage']; // Extract raw Base64 string from data URL list(, $base64Data) = explode(',', $base64Data); $decodedImage = base64_decode($base64Data); if($decodedImage !== false){ file_put_contents('image.png', $decodedImage); echo json_encode(['success' => true, 'message' => 'Image saved successfully']); } else { echo json_encode(['success' => false, 'message' => 'Failed to decode Base64 data']); } } else { echo json_encode(['success' => false, 'message' => 'slotimage field missing from payload']); } }
Ensure Your Frontend uploadImage Sends JSON
function uploadImage(payload) { return fetch('http://localhost/server/index.php?saveImageToFolder=true', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }); }
Important Notes
- Directory Permissions: Make sure the folder where you're saving images has write permissions for the PHP process.
- PHP Config Limits: Check your
php.inifile to ensureupload_max_filesizeandpost_max_sizeare set large enough for your image sizes. - File Naming: Avoid hardcoding
image.png—use unique filenames (like UUIDs) to prevent overwriting existing files.
内容的提问来源于stack exchange,提问作者Matarishvan
相关产品推荐
相关产品推荐

