douzhang3898 2016-02-08 20:00
浏览 28
已采纳

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

Here is what I have tried so far and it isn't working. The HTML file contains:-

<!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>

And the PHP file i.e. 'last_file_action.php' contains this:-

<?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

When I click the submit button I get this error "Problem: Possible file upload attack. Filename:". This is the error I've myself set in PHP file. It shows this error even when I don't select the file to upload. I want it to show Error "Please choose a file to upload" if I don't select a file to upload.

</div>
  • 写回答

2条回答 默认 最新

  • dongqiao6730 2016-02-09 17:53
    关注

    Here is how I did it.

    var formData = new FormData();

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

    The above code is right as long as you have one file and no other input fields. In case you have more input field and multiple file upload in a single form. One should consider target elements by their IDs instead of type $(":file"). Here is how we can get other files:-

     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]);

    Here is how we can get data from input fields of form by targeting their IDs.

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

    In PHP nothing needs to be changed. If we want to get the value of input field we can do it by:-

    $var = $_POST['input_field'];

    And if its a file, we can capture it by this and do the rest of the work as done in the question.

    $_FILES['userfile'] or $_FILE['2nd_file']
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line