php 忽略通过 fetch 提交的文件

问题描述 投票:0回答:1

一直在开发一个 html 和 php 项目,它是一个简单的网络服务器,您可以在其中上传文件,然后该文件将存储在我的 Linux 计算机上,我这样做是为了存储,但我一直遇到一个问题错误,我有一个几乎完美的脚本来保存文件,它应该可以工作,但事实并非如此,错误消息是“没有上传文件”。

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Video</title>
</head>
<body>
    <h1>Upload a Video File</h1>
    <form action="test.php" method="post" enctype="multipart/form-data">
        <label for="file">Select a video file:</label>
        <input type="file" name="file" id="file" accept="video/*" required />
        <input type="submit" value="Upload Video" />
    </form>
</body>
</html>

测试.php:

<?php
// Define the target directory where files will be uploaded
$target_dir = "/home/neo/uploads/";
$uploadOk = 1;

// Check if a file was uploaded
if (isset($_FILES["file"])) {
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    // Check for upload errors
    if ($_FILES["file"]["error"] !== UPLOAD_ERR_OK) {
        echo "Error during file upload: " . $_FILES["file"]["error"];
        exit;
    }

    // Allow certain file formats
    $allowed_ext = array('avi', 'flv', 'wmv', 'mov', 'mp4');
    $file_extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file extension is allowed
    if (!in_array($file_extension, $allowed_ext)) {
        echo "Sorry, only MP4, AVI, FLV, WMV & MOV files are allowed.";
        $uploadOk = 0;
    }

    // Attempt to create the uploads directory if it doesn't exist
    if (!file_exists($target_dir)) {
        if (!mkdir($target_dir, 0755, true)) {
            die("Failed to create directory: " . error_get_last()['message']);
        }
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        // Attempt to move the uploaded file to the target directory
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
} else {
    echo "No file was uploaded.";
}
?>

我尝试使用 php 并保存文件

php
1个回答
-2
投票

我必须在我写入的文件夹上运行 chown www-data:www-data ,由于某种原因第一次不起作用

© www.soinside.com 2019 - 2024. All rights reserved.