如何用新图像替换旧图像的路径。我正在使用ajax和js使用php上传图像。我想用新上传的图像路径替换这个no-image.jpg,并且还想保存图像到数据库的路径,到目前为止我所做的是 我的索引
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<div id="preview"><img src="no-image.jpg" /></div>
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
</div>
</body>
</html>
我的ajaxupload.php
<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
}
else
{
echo 'invalid';
}
}
?>
我的script.js
$(document).ready(function (e)
{
$("#form").on('submit',(function(e)
{
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
答案 0 :(得分:0)
在服务器端:
echo $path;
在ajax成功函数中:
$('#preview img').attr('src',data)