Подтвердить что ты не робот

Загрузка файла PHP с помощью 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'];
?>

Загруженное имя файла не возвращается. Проблема в том, что я не смог получить доступ к загруженному файлу.

Спасибо заранее! Шив

4b9b3361

Ответ 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 File API, который позволяет достичь этого, предполагая, что клиентский браузер поддерживает его.

Ответ 2

Невозможно загрузить файлы с помощью 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);
}

Ответ 3

Нет, нет, вы должны использовать плагин jQuery для асинхронного скачивания файлов. Вы не можете загрузить файл с помощью метода jQuery $.post. Файл будет загружен с помощью скрытого iframe

Другим способом является использование загрузки HTML5 с помощью FileAPI/BlobApi

Ответ 4

Попробуйте загрузить с iframe, потому что вы не можете отправить файл с помощью метода $.post.

Ответ 5

В файле upload.php есть некоторая ошибка.

вы должны изменить свою часть.

echo $file['tmp_name'];

to: -

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