不知道哪里出了问题,上传文件时总是提前无法写入,而服务器文件夹权限我已查看是755,麻烦帮我看看
HTML页面
<?php
foreach ($Lists as $row):
$linkimage = htmlentities($row['linkimage']);
?>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="avatar" required>
<input type="hidden" id="linkimage" value="<?php echo $linkimage;?>">
<input type="submit" value="点击上传">
</form>
<?php endforeach; ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault(); // 阻止表单的默认提交行为
var formData = new FormData(this); // 使用表单元素创建FormData对象
// 有一个隐藏的输入字段或其他方式获取到 linkimageValue
var linkimageValue = document.getElementById('linkimage').value; // 获取隐藏字段的值
// 将 linkimageValue 添加到 formData 中
formData.append('linkimage', linkimageValue);
fetch('upload.php', {
method: 'POST',
body: formData
})
.then(response => response.text()) // 或者response.json(),如果服务器返回JSON
.then(data => {
document.getElementById('sssz-content').innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
upload.php页面
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_FILES['avatar'])) {
$targetDirectory = "../image/upload/";
if (!is_dir($targetDirectory)) {
mkdir($targetDirectory, 0755, true);
}
if (isset($_POST['linkimage'])) {
$linkimage = $_POST['linkimage'];
$linkimage = basename(stripslashes($linkimage));
$originalFileExtension = strtolower(pathinfo($_FILES["avatar"]["name"], PATHINFO_EXTENSION));
$targetFile = $targetDirectory . $linkimage . '.jpg';
if (file_exists($targetFile)) {
die("File with the same name already exists.");
}
$uploadOk = 1;
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $targetFile)) {
echo "文件 " . htmlspecialchars(basename($targetFile)) . " 上传成功。";
} else {
echo "对不起,上传您的文件时出现了错误。";
}
}
} else {
die("Missing 'linkimage' in POST request.");
}
} else {
echo "对不起,没有文件被上传。";
}
?>