在Ajax中上传文件出错

时间:2016-12-28 02:53:13

标签: php jquery html ajax

我无法使用Ajax上传文件。我只想上传一个文件。以下是我所做的代码。

HTML& Ajax的

$(document).ready(function(){
  $("input:submit").on('click', function(e) {
    e.preventDefault();
    var  submit = $("#submit").val(),
    file = document.getElementById('slip_gaji').files[0],
    fd = new FormData();
    fd.append("submit", submit);
    fd.append("slip_gaji", file);
    $.ajax({
      url: "insert-slip.php",
      type: "POST",
      data: fd,
      processData: false,  
      contentType: false   
    }).done(function(data){
        $('#result_insert').html(data)
    });
  });
});

<form id="upload_gaji" name="upload_gaji enctype="multipart/form-data" method="post">
    <fieldset class="account-info">
        <label>
            Slip Gaji <br> 
            <input type="file" name="slip_gaji" id="slip_gaji">
        </label>
    </fieldset>
</form>

PHP - insert-slip.php

<?php
if(isset($_POST["submit"])){
    if (empty($_FILES['slip_gaji']['tmp_name'])) {
        $err[] .= 'No File Selected';
    } else {
        $fname = $_FILES['slip_gaji']['name'];
        $fpath = "uploads/" . date('d-m-Y-H-i-s').'-'.$fname;
        $move = move_uploaded_file($fname, $fpath);  
    }
}

if (!empty($err)) {
    echo '<ol style="color: red;"><li>' . implode('</li><li>', $err) . '</li></ol>';
} else {
    echo 'File Uploaded!';
}

echo '<pre>'; var_dump($_FILES); echo '</pre>';
?>

根据我所做的代码,上传文件夹中没有上传任何文件。如果我使用var_dump($_FILES)。我收到了输出:

array(1) {
  ["slip_gaji"]=>
  array(5) {
    ["name"]=>
    string(12) "cuti_ceo.txt"
    ["type"]=>
    string(10) "text/plain"
    ["tmp_name"]=>
    string(24) "C:\xampp\tmp\php248A.tmp"
    ["error"]=>
    int(0)
    ["size"]=>
    int(196)
  }
}

有人检查错误是什么?

1 个答案:

答案 0 :(得分:1)

$fname = $_FILES['slip_gaji']['name'];
$temp_fpath = $_FILES['slip_gaji']['tmp_name'];
$fpath = "uploads/" . date('d-m-Y-H-i-s').'-'.$fname;
$move = move_uploaded_file($temp_fpath, $fpath);

move_uploaded_file 功能需要完整的文件路径。