簡體   English   中英

使用jQuery Post上傳PHP文件

[英]PHP file-upload using jquery post

讓我知道是否有人知道此代碼有什么問題。

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

上傳的文件名不會返回。 問題是我無法訪問上傳的文件。

提前致謝! 希夫

基本上我想使用jQuery上傳文件

您無法使用AJAX上傳文件。 您可以使用使用隱藏iframe的jquery.form插件:

<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"enctype="multipart/form-data"

另一種可能性是使用HTML5 File API ,它允許您在假定客戶端瀏覽器支持的情況下實現這一點。

不可能使用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);
}

不,不,您應該使用jQuery表單插件異步上傳文件。 您無法使用jQuery $ .post方法上傳文件。 該文件將使用隱藏的iframe上傳

另一種方法是通過FileAPI / BlobApi使用HTML5上傳

您的upload.php出現錯誤。

您應該更改此部分。

echo $file['tmp_name'];

至:-

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

請嘗試使用iframe上傳,因為您無法使用$ .post方法發送文件。

您還可以嘗試使用jQuery uploadify- http: //www.uploadify.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM