【问题标题】:Why is the input file data empty? [closed]为什么输入文件数据为空? [关闭]
【发布时间】:2021-09-26 05:42:00
【问题描述】:

我正在使用 ajax PHP 上传,上传在没有 ajax jQuery 的情况下运行良好。我去谷歌查找更多资源并多次调整我的代码,但在后端仍然得到相同的错误,即文件为空。这是我的代码。

在前端


<input class="input is-link" id="file" name="file" type="file">
<button id="sendImg" class="button">Send</button>
</form>

我的 jQuery 代码

$(function(){
     $("#chatsCard").on('click', '#sendImg', function (e){
     e.preventDefault();
     //alert("test");
    var filedata = $("#file").prop("files")[0];
    var recipient = $("#uname").html();

//alert(filedata);

$.ajax({
      type:'post',
      url:'upload.php',
      contentType:false,
      processData:false,
      cache:false,
      dataType:'json',
data:{
       //rec:recipient,
       filedata
           },
success:function(data){
         alert (data);

}
});//ajax end
});//click end
});//doc end

后端

<?php
   session_start();
   require("assets/db.php");
   $logged = $_SESSION['logged'];

//This is always my ajax response.
if(empty($_FILES['file'])){
    $response = "No picture selected";
    echo json_encode($response);
exit;
}

    $imgFolder = "media/";
    $fileTpath = $_FILES['file']['tmp_name']; 
    $fileSize = filesize($fileTpath);
    $info = finfo_open(FILEINFO_MIME_TYPE);
    $filetype = finfo_file($info, $fileTpath);
    $filetype = explode ("/",$filetype);
    $filetype = $filetype[1];
$allowedFiles = array("jpg" , "png" , "jpeg");

//rename image.
    $newName = uniqid(8);
    $newName = "recipient". 
    $newName. "."  . $filetype;

//check file size
if($fileSize > 21464568){
    $response = "Picture is greater than 2MB, Resize and try again";
    echo json_encode($response);
exit;
}

//check format.
elseif(!in_array($filetype, $allowedFiles)){
    $response= "You are only allowed to upload jpeg,jpg or png";
    echo json_encode($response);
exit;
}

//check for existence of file.
elseif(file_exists($imgFolder.$newName)){
    $response = "Failed!!! Upload again!!!";
    echo json_encode($response);
exit;
}

//move to folder.
else{
  move_uploaded_file($fileTpath,$imgFolder .$newName);
    $recipient = $_POST['rec'];
    $time = date("d-M-y")." at ". date("h:ia");
    $msg = "media";

//insert to messaging
    $q = "INSERT INTO messaging(message,sender, receiver,time) VALUES(?,?,?,?)";
    $stm = $conn->prepare ($q);
    $stm->bind_param("ssss",$msg,$logged,$recipient,$time);
    $stm->execute();

//insert media details

    $q1 = "INSERT INTO media(sender,mediaName,mediaType) VALUES(?,?,?)";
    $stm = $conn->prepare ($q1);
    $stm->bind_param("sss",$logged,$newName,$fileType);
    $stm->execute();

//json response
    $response = "success";
    echo json_encode($response);
exit;
}

?>

由于我删除了 jQuery 并且上传工作正常,我认为问题不是来自后端,所以我通过将其调整到这些来专注于 jQuery

//First change
    var fd = new FormData();
    var file = $("#file").props('files')[0];
    var file data= fd.append("file",filedata);

//This still gives no picture selected.


//Second change
var fd = new FormData($("#mediaPic")[0])

//Passed fd as data but still the same response.

//Tried other stuffs I got on Google to get the image data but still d same response.

【问题讨论】:

  • 这能回答你的问题吗? jQuery Ajax File Upload
  • 您是否检查过浏览器控制台的错误消息。您提供的代码中有许多 blaring 语法错误。
  • "仍然出现同样的错误" - 你有错误吗?它是什么?还是只是你在 php 中的文件是空白/空的?

标签: javascript php html jquery ajax


【解决方案1】:

你只需要post FormData() 对象,Append 方法返回null。数据类型文本是首选。所以最终的 jQuery 代码是:

$(function(){
    $("#sendImg").on('click', function (e){
        e.preventDefault();
        //alert("test");
        var recipient = $("#uname").html();
        
        var form_data   = new FormData();
        var file = $("#file").prop('files')[0];

        form_data.append('file', file);
            
        $.ajax({
            url: 'upload.php',
            dataType: 'text',
            type: 'post',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            success: function(data) {
                alert(data);
            }
        });//ajax end
    });//click end
});//doc end

用form_data添加附加值,提交前简单使用

form_data.append("rec", "value");

【讨论】:

    猜你喜欢
    • 2014-06-16
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多