使用jQuery后PHP文件上传(PHP file-upload using jquery post

2019-06-25 12:39发布

让我知道,如果有人知道什么是与此代码的问题。

基本上我要上传使用jQuery文件

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script type="text/javascript">
    $(document).ready(function(event) {
      $('#form1').submit(function(event) {
        event.preventDefault();
        $.post('post.php',function(data){
           $('#result').html(data);
        });
      });
    });
  </script>  
</head>
<body>
<form id="form1">
  <h3>Please input the XML:</h3>
  <input id="file" type="file" name="file" /><br/>
  <input id="submit" type="submit" value="Upload File"/>
</form>

<div id="result">call back result will appear here</div>

</body>
</html>

和我的PHP“post.php中”

<?php
  echo $file['tmp_name'];
?>

上传的文件名没有返回。 问题是我无法访问上传的文件。

提前致谢! 希夫

Answer 1:

基本上我要上传使用jQuery文件

使用AJAX你不能上传文件。 您可以使用jquery.form它使用一个隐藏的iframe插件:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script type="text/javascript">
        $(document).ready(function(event) {
            $('#form1').ajaxForm(function(data) {
                $('#result').html(data);
            });
        });
  </script>  
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
    <h3>Please input the XML:</h3>
    <input id="file" type="file" name="file" /><br/>
    <input id="submit" type="submit" value="Upload File"/>
</form>

<div id="result">call back result will appear here</div>

</body>
</html>

还要注意enctype="multipart/form-data"的形式。

另一种可能性是使用HTML5文件API ,让你实现这一假设客户端浏览器支持它。



Answer 2:

这是不可能的jQuery .post的$上传文件,neverthless,与文件API和XMLHttpRequest的,这是完全可以上传文件的AJAX,你甚至可以知道有多少数据尚未上传...

$('input').change(function() 
{
    var fileInput = document.querySelector('#file');

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload/');

    xhr.upload.onprogress = function(e) 
    {
        /* 
        * values that indicate the progression
        * e.loaded
        * e.total
        */
    };

    xhr.onload = function()
    {
        alert('upload complete');
    };

    // upload success
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
    {
        // if your server sends a message on upload sucess, 
        // get it with xhr.responseText
        alert(xhr.responseText);
    }

    var form = new FormData();
    form.append('title', this.files[0].name);
    form.append('pict', fileInput.files[0]);

    xhr.send(form);
}


Answer 3:

不,不,不,你应该使用异步上传文件的一个jQuery插件的形式。 你不能用jQuery $。员额方法上传文件。 该文件将与隐藏的iframe上传

另一种方法是使用HTML5上传与FileAPI / BlobApi



Answer 4:

您upload.php的有一定的误差。

你应该改变你的这一部分。

echo $file['tmp_name'];

至:-

echo $_FILES['file']['tmp_name'];


Answer 5:

试着用一个iframe上传,因为你不能用。员额$方法来发送文件。



Answer 6:

您也可以尝试的jQuery uploadify - http://www.uploadify.com/



文章来源: PHP file-upload using jquery post