jQuery实现个人资料页面修改图片成功后,传到数据库,我的页面也能出现修改后的图片,请给出HTML,PHP,MySQL,JS代码
时间: 2024-03-10 09:51:22 浏览: 14
HTML:
```html
<!-- 显示当前图片 -->
<img src="current_image.jpg" id="current-image">
<!-- 上传新图片 -->
<input type="file" id="new-image">
<!-- 保存按钮 -->
<button id="save-button">保存</button>
```
JS:
```js
$(document).ready(function() {
// 当选择新图片时,将其显示在页面上
$('#new-image').change(function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$('#current-image').attr('src', e.target.result);
}
reader.readAsDataURL(file);
});
// 当点击保存按钮时,将新图片上传到服务器
$('#save-button').click(function() {
var file = $('#new-image').get(0).files[0];
var formData = new FormData();
formData.append('image', file);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
if (response.success) {
// 更新数据库中的图片路径
var imagePath = response.imagePath;
$.ajax({
url: 'update.php',
type: 'POST',
data: { imagePath: imagePath },
success: function(response) {
if (response.success) {
alert('保存成功');
} else {
alert('保存失败');
}
}
});
} else {
alert('上传失败');
}
}
});
});
});
```
PHP:
```php
<?php
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
$fileName = $_FILES['image']['name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$fileTempName = $_FILES['image']['tmp_name'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
if (in_array($fileExtension, $allowedExtensions)) {
$filePath = 'images/' . uniqid() . '.' . $fileExtension;
if (move_uploaded_file($fileTempName, $filePath)) {
echo json_encode(array(
'success' => true,
'imagePath' => $filePath
));
} else {
echo json_encode(array(
'success' => false
));
}
} else {
echo json_encode(array(
'success' => false
));
}
} else {
echo json_encode(array(
'success' => false
));
}
?>
```
MySQL:
```sql
UPDATE users SET image_path = 'new_image.jpg' WHERE id = 1;
```