简体   繁体   English

使用PHP和Ajax上载文件

[英]Upload a file using PHP with Ajax

I am trying to upload a file using AJAX and PHP. 我正在尝试使用AJAX和PHP上传文件。

I already do it using forms: 我已经使用表格完成了:

<form action="upload.php" method="POST">
<input type="file" id="idFile" name="fileName" />
</form>

And it works very well, but I really need to do it with AJAX. 而且效果很好,但是我真的需要使用AJAX来实现。

I already have my php script which uploads the file. 我已经有上传文件的php脚本。 I want this script to be excecuted whith AJAX. 我希望该脚本通过AJAX执行。 I want my javascript function to do something like this: 我希望我的javascript函数执行以下操作:

function uploadFile(file) {
    var url = "upload.php?file="+file; //<-- Can I do this?

    xmlhttp = GetXmlHttpObject();
    if (!xmlhttp) {
       alert ("Browser does not support HTTP Request");
       return;
   }
   var xml = xmlhttp;
   xmlhttp.onreadystatechange = function () {
      if (xml.readyState == 4) {
         alert("THE FILE WAS UPLOADED");
      }
   };
   xmlhttp.open("GET",url,true);
   xmlhttp.send(null);

   return true;
}

My question is: Is it posible to pass a file-type variable this way? 我的问题是:可以通过这种方式传递文件类型的变量吗? If not, which is the way I can pass the file variable? 如果没有,那我可以通过哪种方式传递文件变量? Can I use document.getElementById("idFile").value ? 我可以使用document.getElementById("idFile").value吗?

I hope someone could help me Thanks! 我希望有人可以帮助我,谢谢!

You can't upload files via AJAX. 您无法通过AJAX上传文件。 You should use hidden iframe instead. 您应该改用隐藏的iframe。

File upload by ajax is introduced in XHR2 FormData object but this is not supported by old browsers. XHR2 FormData对象中引入了由ajax上传的文件,但是旧的浏览器不支持此功能。 See browsers compatibility table . 请参阅浏览器兼容性表

Unfortunately you can't upload files with Ajax. 不幸的是,您无法使用Ajax上传文件。 Have a look at http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ 看看http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/

I solved the problem in this way. 我以这种方式解决了问题。

<form method="POST" id="formLic" name="formLic" enctype="multipart/form-data">
   <label for="lnumero">Número: </label>
   <input type="text" id="lnumero"/>
   <label for="larchivo">Archivo: </label>
   <input type="file" id="larchivo"/>
</form>
<script>
      $(document).ready(function() { 
        $("form#formLic").submit(function(){
            var formData = new FormData($(this)[0]);
            $.ajax({
                url: "nuevo/uploadInsert.php", // file where you save your data and files
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    // action or message 
                }
            });
            return false;
        });
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM