使用Javascript FormData,AJAX $ .post和PHP进行简单的文件上传

问题描述

因此,我有一个简单的FormData对象,尝试通过该对象上载文件,而不必进行表单提交。 在HTML中,我创建了一个简单的表单,其中包含1)文件上传2)另一个简单的文本输入,用于概念验证。 尝试使用jquery $ .post函数来实现此目的。 PHP文件PHP_SIMPLE_AJAX_IMAGE.PHP只是从相同的发送图像中吐出数据。 HTML是::

<form id="form_image_upload">
    <input type="file" id="input_file" name="input_file_n"></input>
    <label for="input_file" id="label_input_file" >choose file</label>
    <label for="input_file" id="label_small_input_file">...</label><br>
    
    <input type="text" id='simp_text_id' name='simp_text_n' ><br>
    <button id="btn_submit" type="submit" value="submit" class="upload_file">Submit</button>
<form>

<DIV id="Sub_Div_7"> </DIV>

JavaScript

$("#input_file").change(function(e){
    $("#label_small_input_file").html(e.target.files[0].name);
    });

$("#form_image_upload").submit(function(e){
        e.preventDefault();
        let fd = new FormData(this);
    //  alert( fd.get('input_file_n').name);  //This works
    //  alert( fd.get('simp_text_n'));  //This works
        
    $.post("PHP/PHP_SIMPLE_AJAX_IMAGE.PHP",fd,function(data){ 
                            $("#Sub_Div_7").html(data); });
});

PHP

<?PHP 
if(isset($_FILES['input_file_n'])
{       $F_name = $_FILES['input_file_n']['name'];
        $F_tmpnm = $_FILES['input_file_n']['tmp_name'];
        $F_type = $_FILES['input_file_n']['type'];
        $F_size = $_FILES['input_file_n']['size'];      }

$text_1 = isset($_POST['simp_text_n']) ? $_POST['simp_text_n'] : "NULL";
echo "Filename: " . $F_name . " Tempname: " . $F_tmpnm . " Type: ". $F_type  . " Size: " . $F_size . " TextInput: " . $text_1 ;
?>

当我把两行放在alert(fd.get('input_file_n')。name); alert(fd.get('simp_text_n'));我收到了具有正确文件名的警报,因此fd对象的确捕获了表单数据。但是,当我执行该命令时,在控制台中出现了一个错误..在$ .post(...)所在的javascript行中出现了类似“ Uncaught TypeError:Illegal invocation”的错误提示。 ?

JS Error

解决方法

遵循以下说明:

  1. 您应该在html部分中输入类型为file的输入:
<input type="file" id="file_target">
  1. 为文件输入添加更改事件
$('#file_target').change(function (e) {
  e.preventDefault();

  // for single file upload
  uploadFile(this.files[0]);

  // for multiple file upload
  $.each(this.files,function (k,file) {
    uploadFile(file);
  });
});
  1. 添加可以上传文件的uploadFile函数:

您可以在此处验证要上传的文件

function uploadFile(file) {
  // some validation like size or dimension
  //...

  var urlPath = 'php_script_file_for_upload';

  // create data to be send
  var fd = new FormData();
  fd.append('file_data',file);
  
  // if you do not want use jQuery
  var xhr = new XMLHttpRequest();
  // third parameter is set to be async request
  xhr.open('POST',urlPath,true);
  xhr.send(fd);

  // if you do use jQuery
  $.ajax({
    method: 'POST',url: urlPath,data: fd
  });
}
  1. PHP脚本文件
if(!empty($_FILES['file_data']))
  {
  $path = "uploads/";
  $path = $path . basename( $_FILES['file_data']['name']);

  if(move_uploaded_file($_FILES['file_data']['tmp_name'],$path)) {
    // successful upload
  } else{
    // error during upload
  }
}

如果您不需要使用ajax方法,请参见https://gist.github.com/taterbase/2688850

,

您只需fetch即可将do post请求发送到您的backend php文件中。

原因对您不起作用的原因是,$.post无法处理formData对象本身-因此为什么会收到该错误。

通过Post方法使用fetch

实时演示:

$("#input_file").change(function(e) {
  $("#label_small_input_file").html(e.target.files[0].name);
});

$("#form_image_upload").submit(function(e) {
  e.preventDefault();
  let fd = new FormData($(this)[0]) //store data using $(this)[0]

  //Using Simple Fetch API
  fetch('PHP/PHP_SIMPLE_AJAX_IMAGE.php',{
      method: 'post',body: fd,})
    .then(function(data) {
      $("#Sub_Div_7").html(data);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form_image_upload">
  <input type="file" id="input_file" name="input_file_n" />
  <label for="input_file" id="label_input_file">choose file</label>
  <label for="input_file" id="label_small_input_file">...</label><br>

  <input type="text" id='simp_text_id' name='simp_text_n'><br>
  <button id="btn_submit" type="submit" value="submit" class="upload_file">Submit</button>
  <form>

<div id="Sub_Div_7"> </div>

使用$.ajax和post方法

实时演示:

$("#input_file").change(function(e) {
  $("#label_small_input_file").html(e.target.files[0].name);
});

$("#form_image_upload").submit(function(e) {
  e.preventDefault();
  let fd = new FormData($(this)[0])
  $.ajax({
    url: 'PHP/PHP_SIMPLE_AJAX_IMAGE.php',type: 'POST',data: fd,processData: false,contentType: false,success: function(data) {
      $("#Sub_Div_7").html(data);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form_image_upload">
  <input type="file" id="input_file" name="input_file_n" />
  <label for="input_file" id="label_input_file">choose file</label>
  <label for="input_file" id="label_small_input_file">...</label><br>

  <input type="text" id='simp_text_id' name='simp_text_n'><br>
  <button id="btn_submit" type="submit" value="submit" class="upload_file">Submit</button>
  <form>

<div id="Sub_Div_7"> </div>