如何将文件从JavaScript传递到PHP?

如何将文件从JavaScript传递到PHP?,javascript,php,ajax,Javascript,Php,Ajax,是否可以将文件从JavaScript传递到PHP?(最好使用ajax)。如果我们有以下代码: <!DOCTYPE html> <html> <body> <input type='file' id='upld' onChange=' f=this.files[0] '> <input type='button' onClick='ajax_pass()'> <script>

是否可以将文件从JavaScript传递到PHP?(最好使用ajax)。如果我们有以下代码:

<!DOCTYPE html>
 <html>

  <body>

   <input type='file' id='upld' onChange=' f=this.files[0] '> 
   <input type='button' onClick='ajax_pass()'>

     <script>

      function ajax_pass()
      {

       console.log(f);

        //Send 'f' using ajax to php imaginary file...
      }

     </script>

  </body>

 </html>

函数ajax_pass()
{
控制台日志(f);
//使用ajax将“f”发送到php虚拟文件。。。
}

我是JS编程新手,无法想象POST或GET如何包含整个图像。您能给我澄清一下吗?

HTML代码

<input id="myfile" type="file" name="myfile" />
<button id="upload" value="Upload" />
$(document).on("click", "#upload", function() {
    var file_data = $("#myfile").prop("files")[0];   // Getting the properties of file from file field
    var form_data = new FormData();                  // Creating object of FormData class
    form_data.append("file", file_data)              // Appending parameter named file with properties of file_field to form_data
    form_data.append("user_id", 123)                 // Adding extra parameters to form_data
    $.ajax({
                url: "/upload_file.php",
                dataType: 'script',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         // Setting the data attribute of ajax with file_data
                type: 'post'
       });
});
print_r($_FILES);
print_r($_POST);
Php代码

<input id="myfile" type="file" name="myfile" />
<button id="upload" value="Upload" />
$(document).on("click", "#upload", function() {
    var file_data = $("#myfile").prop("files")[0];   // Getting the properties of file from file field
    var form_data = new FormData();                  // Creating object of FormData class
    form_data.append("file", file_data)              // Appending parameter named file with properties of file_field to form_data
    form_data.append("user_id", 123)                 // Adding extra parameters to form_data
    $.ajax({
                url: "/upload_file.php",
                dataType: 'script',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         // Setting the data attribute of ajax with file_data
                type: 'post'
       });
});
print_r($_FILES);
print_r($_POST);

您可以尝试使用类库,就像唯一可能的方法是Ajax一样。这可以完成以下工作: