如何通过AJAX和PHP上传表单中的文件?

时间:2016-02-08 20:00:12

标签: php jquery ajax html-form-post

这是我到目前为止所尝试过的,但它无效。 HTML文件包含: -

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form Generator | Upload Driver Specification Sheet</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
        <script type='text/javascript'>
            function submit_form() {

                var formData = new FormData($(this)[0]);

                $.ajax({
                    url: 'last_file_action.php',
                    type: 'POST',
                    data: formData,
                    async: false,
                    success: function (data) {
                        $('#results').html(data);
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });

                return false;
            }
        </script>
    </head>
    <body class="gray-bg3_full">
        <form class="m-t" role="form" id='data'  method="post" enctype="multipart/form-data">
            <input type="hidden" name="MAX_FILE_SIZE" value="2000000">

            <div class="form-group">
                <p id='new_project_text'>Please include your Product spec sheet: </p>
                <input class="btn btn-primary-save btn-block" type="file" name="userfile" /> <i class="fa fa-upload"></i> &nbsp;  <br/>
            </div>
            <button type= 'button' id="submit_driver" class="btn btn-warning block full-width m-b m-t" onclick='submit_form()'>Submit</button>
        </form>
        <div id='results'></div>
    </body>
</html>

PHP文件,即'last_file_action.php'包含: -

<?php

if ($_FILES['userfile']['error'] > 0)
{
    switch ($_FILES['userfile']['error'])
    {
        case 1:
            echo "File exceeded upload_max_filesize";
            break;
        case 2:
            echo "File exceeded max_file_size";
            break;
        case 3:
            echo "File only partially uploaded";
            break;
        case 4:
            echo "Please choose a file to upload";
            break;
        case 6:
            echo "Cannot upload file: No temp directory specified";
            break;
        case 7:
            echo "Upload failed: Cannot write to disk";
            break;
    }
    exit;
}
$upfile = 'productinformation/';

if (is_uploaded_file($_FILES['userfile']['tmp_name']))
{
    if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile))
    {
        echo "Problem: Could not move file to destination directory";
        exit;
    }
}
else
{
    echo "Problem: Possible file upload attack. Filename: ";
    echo $_FILES['userfile']['name'];
    exit;
}



// remove possible HTML and PHP tags from the file's contents
$contents = file_get_contents($upfile);
$contents = strip_tags($contents);
file_put_contents($_FILES['userfile']['name'], $contents);
// show what was uploaded

当我点击提交按钮时,我收到此错误“问题:可能的文件上传攻击。文件名:”。这是我自己在PHP文件中设置的错误。即使我没有选择要上传的文件,它也会显示此错误。如果我没有选择要上传的文件,我希望它显示错误“请选择要上传的文件”。

2 个答案:

答案 0 :(得分:1)

var formData = new FormData();
formData.append("userfile", $(":file")[0].files[0]);

答案 1 :(得分:0)

我是这样做的。

var formData = new FormData();

formData.append(&#34; userfile&#34;,$(&#34;:file&#34;)[0] .files [0]);

只要您有一个文件而没有其他输入字段,上面的代码就是正确的。如果您在单个表单中有更多输入字段和多个文件上载。人们应该通过ID而不是$(&#34;:file&#34;)来考虑目标元素。 以下是我们如何获取其他文件: -

&#13;
&#13;
 var formData = new FormData();
formData.append("first_file", $("#1st_file_id")[0].files[0]);
formData.append("2nd_file", $("#2nd_file_id")[0].files[0]);
formData.append("3rd_file", $("#3rd_file_id")[0].files[0]);
&#13;
&#13;
&#13;

以下是我们如何通过定位其ID来从表单的输入字段中获取数据。

&#13;
&#13;
  formData.append("input_field", $("#input_field_id").val());
&#13;
&#13;
&#13;

在PHP中没有什么需要改变的。如果我们想获得输入字段的值,我们可以通过以下方式完成: -

&#13;
&#13;
$var = $_POST['input_field'];
&#13;
&#13;
&#13; 如果它是一个文件,我们可以通过这个捕获它,并按照问题所做的其余工作完成。

$_FILES['userfile'] or $_FILE['2nd_file']