使用jquery post发布PHP文件

时间:2012-06-15 07:53:10

标签: php jquery file-upload

如果有人知道此代码的问题,请告诉我。

基本上我想使用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'];
?>

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

提前致谢! 希夫

6 个答案:

答案 0 :(得分:17)

  

基本上我想使用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 File API,允许您在客户端浏览器支持的情况下实现该目标。

答案 1 :(得分:6)

无法使用jQuery $ .post上传文件,无论如何,使用文件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);
}

答案 2 :(得分:5)

不不不,你应该使用jQuery表单插件来异步上传文件。您无法使用jQuery $ .post方法上传文件。该文件将上传隐藏的iframe

另一种方法是使用FileAPI / BlobApi

上传HTML5

答案 3 :(得分:1)

您的upload.php有一些错误。

你应该改变这一部分。

echo $file['tmp_name'];

来: -

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

答案 4 :(得分:0)

尝试使用iframe上传,因为您无法使用$ .post方法发送文件。

答案 5 :(得分:-1)

你也可以试试jquery uploadify - http://www.uploadify.com/