我试图使用php将我的PHP代码转换为javascript ajax。你可以帮我纠正错误,因为我的php代码仍在激活。
html代码:
<form method="post" enctype="multipart/form-data" action="testadd.php">
<input type="file" name="image" id="image">
<br/>
<input type="submit" name="submit" value="upload" id="submit">
</form>
PHP:
<?php
if(isset($_POST['submit'])){
if(getimagesize($_FILES['image']['tmp_name']) == false){
echo "Please select an image";
echo "<br/>";
}else{
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
saveImage($name, $image);
}
}
displayImage();
function saveImage($name, $image){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("INSERT INTO images(id, name, image) VALUES(38836929, '$name', '$image') ON DUPLICATE KEY UPDATE image='$image', name='$name'");
$stmt->execute();
}
function displayImage(){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("SELECT * FROM images");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_OBJ)){
echo '<img height="24" width="24" src="data:image;base64,' . $result->image . '">';
echo '<br/>';
echo $result->name . ' ';
}
}
?>
的javascript:
$(document).ready(function(){
$("#submit").click(function(){
var image = document.getElementById("image").value;
alert(" " + image);
if(image == ""){
alert("please select image");
}else{
$.ajax({
type: "POST",
url: "testadd.php",
data: "image=" + image,
success: function(data){
if(data == success){
alert("test");
}else{
alert("fail");
}
}
});
}
return false;
});
});
请你检查一下应该是什么问题才能修复。
答案 0 :(得分:0)
AJAX必须有内容Type,ProcessData才能上传图片文件
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
success : function(data){
//Do stuff for ahed process....
}
});