使用AJAX上传PDF

时间:2016-03-26 21:12:06

标签: javascript php jquery ajax file-upload

我尝试使用AJAX上传PDF文档,但它仍然因未知错误而失败。我做错了什么?

HTML文件:

<form id="document">
    <p>
        Title<br>
        <input type="text" name="name" size="30">
    </p>
    <p>
        Please specify a file, or a set of files:<br>
        <input type="file" name="datafile" size="40">
    </p>
    <div>
        <input id="submit-button" type="button" value="Send">
    </div>
</form>

<script src="jquery.js"></script>
<script>
    $(document).ready(function(){
        $('#submit-button').click(function() {
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: "upload_document.php",
                data:  $("#document").serialize(),
                success : function(data){
                    alert(data.message);
                }, error : function(data) {
                    alert(data.message);
                }
            });
        });
    });
</script>

PHP文件(upload_document.php)

<?php

header("Access-Control-Allow-Origin: *");

try {
    $id = "[RANDOM_GENERATED_GUID]";

    $targetDir = "../../../../modules/sites/documents/";
    if (!is_dir($targetDir)) {
        if (!mkdir($targetDir, 0777, true)) {
            throw new Exception("Unable to upload your document. We were unable to create the required directories");
        }
    }

    $targetFile = $targetDir . $id . ".pdf";
    $fileType = pathinfo($targetFile, PATHINFO_EXTENSION);

    if (file_exists($targetFile)) {
        throw new Exception("Unable to upload your document. The file already exists");
    }

    if ($_FILES["datafile"]["size"] > 2000000) {
        throw new Exception("Unable to upload your document. The file is to large (Maximum of 2MB)");
    }

    if ($fileType != "pdf") {
        throw new Exception("Unable to upload your document. Only PDF documents can be uploaded");
    }

    if (!move_uploaded_file($_FILES["datafile"]["tmp_name"], $targetFile)) {
        //Keeps failing here with error code 0
        throw new Exception("Unable to upload your document. There was an error uploading the file");
    }

    echo json_encode(array(
        "error" => false,
        "message" => "Your document was successfully uploaded"
    ));
} catch (Exception $ex) {
    echo json_encode(array(
        "error" => true,
        "message" => $ex->getMessage()
    ));
}

我还检查了服务器,并且正在成功创建目录。谢谢你的帮助!

修改
如果我在表单上设置操作,并使用提交按钮,则完全相同的PHP脚本可以正常工作。我想使用AJAX的唯一原因是在收到响应后显示模态对话框

1 个答案:

答案 0 :(得分:0)

当你开始使用AJAX POST时,应该在$ _POST而不是$ _FILES中查找已发布的参数。

这是因为$ _FILES是通过多部分帖子上传的文件的缓存。由于您已将其序列化并使用AJAX发送,因此PHP会解析JSON并将所有内容放在$ _POST

查看here示例