PHP文件上传,ajax显示错误

File upload in PHP, ajax shows error

本文关键字:ajax 显示 错误 文件 PHP      更新时间:2024-06-26

我正在尝试上传一个图像文件。

这是我的Html

    <form class="form-horizontal" role="form" enctype="multipart/form-data">
    <div class="form-group">
        <label for="a" class="control-label col-sm-2">A:</label>
        <input type="text" class="form-control col-sm-10" id="a">
    </div>
     <div class="form-group">
        <label for="b" class="control-label col-sm-2">B:</label>
        <input type="text" class="form-control col-sm-10" id="b">
    </div>
    <div class="form-group">
        <label for="c" class="control-label col-sm-2">C:</label>
        <input type="text" class="form-control col-sm-10" id="c">
    </div>
    <div class="form-group">
        <label for="d" class="control-label col-sm-2">D:</label>
        <input type="text" class="form-control col-sm-10" id="d">
    </div>   
    <div class="form-group">
        <label for="fupload" class="control-label col-sm-2">Upload image:</label>
        <input type="file" class="form-control col-sm-10" id="fupload">
    </div>   
    <button type="button" class="btn-lg btn-primary" style="margin-left:200px" id="new_save" onclick='save_all();'>Save</button>
</form>

我的javascript代码

var a= _("a").value; //the _ function returns document.getElementById(x)
var b = _("b").value;
var c = _("c").value;
var d = _("d").value;
var file_data = $("#fupload").prop("files")[0];  
var fileup = new FormData();                  
fileup.append("file", file_data)
var ajax = ajaxObj("POST", "./phps/saveall.php");
ajax.onreadystatechange = function() { 
        alert(ajax.responseText);
    }
ajax.send("a="+a+"&b="+b+"&c="+c+"&d="+d+"&fileup="+fileup);

最后我的PHP

   $a = preg_replace('#[^a-z0-9()., ]#i', '', $_POST['a']);
   $b = preg_replace('#[^a-z0-9()., ]#i', '', $_POST['b']);
   $c= htmlentities($_POST['c']);
   $c= mysqli_real_escape_string($db_conx, $c);
   $d = htmlentities($_POST['d']);
   $d = mysqli_real_escape_string($db_conx, $d);
   $fup =  $_POST['fileup'];
   //processing a-d
   //this is where the problem comes
   move_uploaded_file($_FILES[$fup]['tmp_name'], '../lyrics/'.$a.'.png');

当我运行这个时,变量a-d得到了很好的处理,但文件没有上传,但显示了以下错误

"注意:未定义的索引:[object FormData]"

我该怎么解决这个问题?

首先告诉FORM它将包含一个上传的对象(或更多)。

<form enctype="multipart/form-data" action="...put your URL here..." method="POST">

点击此处阅读更多:

http://php.net/manual/en/features.file-upload.post-method.php

问题就在这里:

ajax.send("a="+a+"&b="+b+"&c="+c+"&d="+d+"&fileup="+fileup);

您正试图将FormData对象附加到字符串中。相反,您应该将所有其他值附加到FormData对象并发送它。

var fileup = new FormData();                  
fileup.append("file", file_data);
fileup.append("a", a);
fileup.append("b", b);
fileup.append("c", c);
fileup.append("d", d);
ajax.send(fileup);