无需表单提交:使用AJAX和PHP将图片存入MySQL数据库
Hey there! Let's break down what's going wrong with your image upload code and fix it step by step—you're really close, just a few key issues to address:
First, the AJAX Mistake
You're wrapping your FormData object inside another object ({ 'BEimage': $form_data }), which breaks how multipart form data is parsed by PHP. Instead, you need to pass the FormData directly as the data value. Also, if you need to send CustomerID and Username along with the image, append them to the FormData too.
Fixed AJAX Code:
var $file_data = $('#HTMLmyimage').prop('files')[0]; var $form_data = new FormData(); // Append the image file $form_data.append('file', $file_data); // Append other required fields (adjust values to match your actual data) $form_data.append('CustomerID', 'your_customer_id_here'); $form_data.append('Username', 'your_username_here'); $.ajax({ type: "POST", enctype: 'multipart/form-data', processData: false, // Critical: prevents jQuery from messing with form data contentType: false, // Critical: lets the browser set the correct content type url: "PHPURL", data: $form_data, // Pass FormData directly, no wrapping success: function(result) { alert('User Added') }, error: function(result) { alert('Error: ' + result.responseText); // Show actual error details } });
Next, the PHP Issues
- You're trying to get the file via
$request->getParam('BEimage'), but file uploads live in the$_FILESsuperglobal, not in request params. - Your SQL query has a major SQL injection risk—you're directly inserting
$CustomerIDand$Usernameinto the query instead of using parameter binding. - When storing binary image data, you should specify the parameter type as
PDO::PARAM_LOBto ensure proper handling.
Fixed PHP Code:
// First, verify the file uploaded successfully if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) { $imageTmpPath = $_FILES['file']['tmp_name']; $imageData = file_get_contents($imageTmpPath); // Retrieve other form fields from $_POST $CustomerID = $_POST['CustomerID']; $Username = $_POST['Username']; // Use full parameter binding to avoid SQL injection $sql4 = "INSERT INTO customerlocation (CustomerID, Username, img) VALUES (:CustomerID, :Username, :img)"; $stmt4 = $db->prepare($sql4); // Bind all parameters (note the PDO::PARAM_LOB for binary data) $stmt4->bindParam(':CustomerID', $CustomerID); $stmt4->bindParam(':Username', $Username); $stmt4->bindParam(':img', $imageData, PDO::PARAM_LOB); if($stmt4->execute()) { echo "Upload successful"; } else { echo "Database error: " . implode(", ", $stmt4->errorInfo()); } } else { // Handle file upload errors $errorMsg = $_FILES['file']['error'] ? "Error code: " . $_FILES['file']['error'] : "No file uploaded"; echo "File upload failed: " . $errorMsg; }
Key Notes to Remember
- Always validate file uploads (check file type, size, and error status) before processing them.
- Never insert raw user input directly into SQL queries—parameter binding is non-negotiable for security.
- Using
PDO::PARAM_LOBensures your binary image data is stored correctly in the database.
内容的提问来源于stack exchange,提问作者style237
相关产品推荐
相关产品推荐

