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

3

是否可以通过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>

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


你可以尝试使用类似于http://fineuploader.com/的库。 - jcubic
唯一可能的方法是使用 Ajax。 - Amrinder Singh
这段代码可以实现该功能: https://mobiarch.wordpress.com/2013/01/02/uploading-file-using-xmlhttprequest-level-2/ - Ramanlfc
1个回答

7

HTML代码

<input id="myfile" type="file" name="myfile" />
<button id="upload" value="Upload" />

Jquery 代码

$(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'
       });
});

PHP 代码

print_r($_FILES);
print_r($_POST);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接