【问题标题】:Upload files with ajax and php使用ajax和php上传文件
【发布时间】:2014-09-07 02:13:09
【问题描述】:

我有一个完整的 php 文件脚本。 它是一个带有浏览按钮的数据表,用于向数据库添加新视频并将其重新加载到数据表中

问题是在数据库中创建了条目,但文件从未从其原始位置复制到库/视频文件夹。

我已经尝试过并尝试过让它继续运行,似乎 php move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path) 的部分从未执行过或其他什么。

<?php

include 'config.php';

$sTable = "media";


$rootFolder = '../video/';
$libraryFolder = '../video/library/';
$priorityFolder = '../video/priority/';

if (!is_dir($rootFolder)) {
    mkdir($rootFolder, 0777, true);
}
if (!is_dir($libraryFolder)) {
    mkdir($libraryFolder, 0777, true);
}
if (!is_dir($priorityFolder)) {
    mkdir($priorityFolder, 0777, true);
}



if(isset($_POST['script'])){


    try {
        $db = new PDO(
            "mysql:host=".Config::$DB_HOST.";dbname=".Config::$DB_DATABASE.";charset=utf8",
            Config::$DB_USERNAME,
            Config::$DB_PASSWORD
        );
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        print_r('CONNECTED TO DATABASE');
    } catch(PDOException $e) {
        print_r('ERROR CONNECTING TO DATABASE');
    }


    switch($_POST['script']){

        case 'fetchAll':
            $query = $db->prepare("SELECT * FROM $sTable");
            $query->execute();
            echo json_encode(array('media' => $query->fetch()));
            break;



        case 'insert':
            $target = $_POST['file'];
            $target_path = "../video/library/";
            $target_path = $target_path . $target;


            if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
                echo "The file ".  $target ." has been uploaded";

            } else{
                echo "There was an error uploading the file, please try again!";
            }


            $data = array(
                ':name' => $target,
                ':path' => $target_path);
            $table = 'media';
            $fields = array('name', 'path');
            $parameters = array(':name', ':path');
            $param = implode(',',$parameters);

            $stmt = $db->prepare("INSERT INTO {$table} (name, path) VALUES (:name, :path)");

            try {
                $db->beginTransaction();
                $stmt->execute(array("$parameters[0]" => $data[':name'], "$parameters[1]" => $data[':path']));
                $db->commit();
                print $db->lastInsertId();
            } catch(PDOExecption $e) {
                $db->rollback();
                print "Error!: " . $e->getMessage() . "</br>";
            }


            break;

        default:
            print_r('default');
            break;


    }
}


$db = null;










?>

<script>
    $(document).ready( function () {
        $('#vidlib_dtable').dataTable( {
            "dom": '<"top"f>rt<"bottom"lp><"clear">'
        } );
    } );
</script>




<script>
    $("#uploadedfile").on("change", function(){
        var file = this.files[0];
        var fileName = file.name;
        var fileSize = file.size;
        var fileType = file.type;
    });


    $(document).ready( function () {
        $("#vidUpdSubmit").click(function() {

            oFiles = document.getElementById("uploadedfile").files[0];
            nFiles = oFiles.name;
            nSize = oFiles.size;

            var myFile = $('#uploadedfile').prop("files")['name'];
            var url = "./inc/MediaScripts.php"; // the script where you handle the form input.

            $.ajax({
                type: "POST",
                data: ({'script':'insert',
                    'file': nFiles}
                    ),
                cache: false,
                success:function(data){
                    alert(data);
                },error:function(errormsg){
                    alert('EPPIC FAIL');
                }
            });

            return false; // avoid to execute the actual submit of the form.
        });
    } );
</script>





<div class="site_window_header">File manager</div>
<div>
    <div class="vl_buttonPane">
        <form  id="vidUpdForm" action="" method="POST">
            <input type="hidden" name="sctipt" value="insert" id="sctipt"/>
            Choose a file to upload: <input name="uploadedfile" id="uploadedfile" type="file" /><br />
            <input type="submit" id="vidUpdSubmit" value="Upload File" />
        </form>
    </div>
    <div class="vl_rightPane">

        <table id="vidlib_dtable" class="display">
            <thead>
            <tr>
                <th>Name</th>
                <th>Title</th>
                <th>File path</th>
                <th>Duration</th>
                <th>Date uploaded</th>
                <th>Uploaded by</th>
                <th>Key words</th>
                <th>Comments</th>
            </tr>
            </thead>
        </table>
    </div>
</div>

HERE is a link to a dropbox zip file with a manageable working copy of the program

解决方案:感谢 -> Alexander Ceballos

Upload Multiple Files with PHP and JQuery

【问题讨论】:

  • 那么您是否收到错误消息“出现错误...”?
  • @PatrickQ 你遇到了什么错误?
  • 这不是我的代码。我不是运行它的人。您有两个与这部分代码相关的 echo 语句。其中一个应该被执行。你看到的是哪一个,错误还是成功?
  • @PatrickQ 好的。我什么也没得到,但似乎move_uploaded_file($_FILES['uploadedfile']['tmp_name'] 位给出了问题。这是文件应该从 PHP 的临时文件夹复制到目标文件夹的位置。但是为什么不是……?数据库中的条目已创建。只是副本就是问题所在。您对$_FILES 了解更多,或许能给我一些见解?

标签: php jquery ajax file-upload


【解决方案1】:

所以问题不在于$_FILES,问题在于您没有提交文件。您正在使用 ajax 使用data:({'script':'insert', 'file':nfiles}) 发布文件名(nfiles)和值“插入”,这允许您的脚本处理表更新。但是,您实际上并没有发布文件,因为没有提交表单,所以 $_FILES['uploadedfile] 实际上是未定义的。您要么需要实际提交表单,然后才能以当前编写脚本的方式处理文件移动。或者您需要将该文件添加到您的 ajax 帖子中,这将要求您创建一个表单数据对象 var formData = new FormData();。查看此页面了解更多关于uploading files with ajax 的信息或查看this 示例。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 2014-05-02
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多