【问题标题】:File Upload with PHP and jQuery使用 PHP 和 jQuery 上传文件
【发布时间】:2021-02-12 13:39:27
【问题描述】:

我正在制作一个非常简单的文件上传 Web 应用程序,我用一个简单的 POST 请求直接对 PHP 页面进行了测试,它可以正常工作,但不能使用 Ajax。 我认为这与我使用 FormData() 的方式有关,但我用谷歌搜索并尝试了使用 FormData 的其他解决方案,但它们都没有奏效,所以我不完全确定问题出在哪里。 我只是在控制台中收到这种类型的错误:

Object { readyState: 0, getResponseHeader: getResponseHeader(key), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(name, value), overrideMimeType: overrideMimeType(type), statusCode: statusCode(map), abort: abort(statusText), state: state(), always: always(), catch: catch(fn), … }

HTML:

     <form id="upForm" enctype="multipart/form-data">
        <input hidden name="MAX_FILE_SIZE" value="3000000">
        <input id = "file" type="file" name="file"> <br>
        <input type="submit" value="upload">
    </form>

JS 脚本:

$(document).ready(function (e) {
    $("#upForm").on('submit', function (e) {
        $.ajax(
            {
                type: 'POST',
                dataType: 'JSON',
                url: '/data/controls.php',
                processData: false,
                contentType: false,
                cache: false,
                data: new FormData(this),
                // beforeSend: // TO-DO
                success: function (response) {
                    // file uploaded
                    console.log(response);
                },
                error: function (response) {
                    console.log(response)
                }
            }
        )
    }
    )
}
)

controls.php:

$uploadDir = "../upload/";
$response = array(
    'status' => 0,
    'message' => 'Oops!'
);

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    //test file extension
    //test file size
    if ($_FILES['file']['size'] > 3000000){
        $response['status'] = 0;
        $response['message'] = 'File size too big!';

    } else {
        $allowedTypes = array('jpg', 'png', 'jpeg', 'gif');
        $fileName = basename($_FILES['file']['name']);
        $filePath = $uploadDir . $fileName;
        $fileType = pathinfo($filePath, PATHINFO_EXTENSION);

        if (in_array($fileType, $allowedTypes)){
            if(move_uploaded_file($_FILES['file']['tmp_name'], $filePath)){
                $response['status'] = 1;
                $response['message'] = 'Something went wrong :(';
            }
        } else {
            $response['status'] = 2;
            $response['message'] = 'File format not allowed!';
        }
    }
    if ($response['status'] = 1){
        $PDOinst= DBconnect::getInstance();
        $PDO = $PDOinst->getConnection();
        $sqlString = "INSERT INTO fileUpload values (NULL, :fname, :size, :upDate)";
        $query = $PDO->prepare($sqlString);
        $paramArray = array(
            'fname' => $_FILES['file']['name'],
            'size' => $_FILES['file']['size'],
            'upDate' => date("d-m-Y (G:i)")
        );
        $query->execute($paramArray);
        $response['status'] = 3;
        $response['message'] = 'File uploaded successfully!';
    }
    echo json_encode($response);
}

echo json_encode($response);

【问题讨论】:

  • 这甚至不会使用 AJAX - 你没有告诉 javascript 阻止回发(使用 e.preventDefault())。所以它只会提交表单,此时 Javascript 会停止运行,因为浏览器会丢弃当前页面。
  • 您需要在提交处理程序中调用e.preventDefault() 以防止标准表单提交
  • 除此之外,已经在网上的一些地方提供了使用 jQuery/AJAX 上传文件的示例,包括这里的旧问题。我假设您可能已经尝试从那些中复制。因此,您可以对照这些示例检查其余代码。但看起来你可能走对了。
  • 这能回答你的问题吗? jQuery AJAX file upload PHP
  • 编辑:实际上是的,它确实回答了我的问题,抱歉,谢谢!

标签: php jquery ajax file


【解决方案1】:

请在 ajax 函数中添加这 2 行 enctype: 'multipart/form-data', mimeType: 'multipart/form-data',

$.ajax(
                {
                    type: 'POST',
                    dataType: 'JSON',
                    url: '/data/controls.php',
                    processData: false,
                    contentType: false,
                    enctype: 'multipart/form-data',
                    mimeType: 'multipart/form-data',
                    cache: false,
                    data: new FormData(this),
                    // beforeSend: // TO-DO
                    success: function (response) {
                        // file uploaded
                        console.log(response);
                    },
                    error: function (response) {
                        console.log(response)
                    }
                }
            )

【讨论】:

  • 这到底是做什么的?我已经按照一些成员的建议通过添加 e.preventDefault() 来修复它,所以我对这种方法有点好奇。
猜你喜欢
  • 2017-02-15
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
相关资源
最近更新 更多