duanli6834 2016-10-31 22:45
浏览 34

上传文件时出现JQuery错误[重复]

This question already has an answer here:

I want to upload a file to a web server using HTML, JavaScript, and PHP.

My HTML looks like this:

<form method="post" enctype="multipart/form-data" name="uploadForm"> 
    <input type="file" name="uploadFile" onchange="uploadplz();">
    <!-- <input type="submit" name="upload_submit" value="Upload"> -->
</form>

The submit button is commented out because I have to use only one button to upload and submit the file. I have an onchange attribute that call a JavaScript function. The JavaScript function then calls a PHP function using an AJAX call.

My JavaScript/AJAX looks like this:

<script type="text/javascript">
    function uploadplz() {
        $.ajax({
            type: "POST",
            url: "file.php",
            data: "uploadForm",
            success: function(response) {
                alert(response);
            }
        });
    }
</script>

PHP isset looks like this:

if(isset($_POST["uploadForm"])) {
    upload_file();
}

PHP Function looks like this:

function upload_file() {
    $dir = "files/";
    $target_file = $dir.basename($_FILES["uploadFile"]["name"]);

    echo $target_file."</br>";

    if(move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) {
        echo $target_file." uploaded successfully.</br>";
    } else {
        echo "Error uploading</br>";
    }
}

When using 2 buttons, the PHP works fine i.e uploads file. I am assuming my AJAX is wrong when trying to use one button. The PHP function returns the Error uploading message and a blank file name.

Any suggestions?

</div>
  • 写回答

1条回答 默认 最新

  • douzong7283 2016-10-31 22:50
    关注

    You are only uploading the string "uploadForm" not the File object. Use FormData() to upload the <form>, see jQuery Ajax File Upload

    function uploadplz() {
        $.ajax({
            type: "POST",
            url: "file.php",
            data: new FormData(document.querySelector("form")),
            processData: false,
            contentType: false,
            success: function(response) {
                alert(response);
            }
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 python进程启动打包问题
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题