使用jquery post发布PHP文件

Shi*_*hiv 13 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>
Run Code Online (Sandbox Code Playgroud)

和我的php'post.php'

<?php
  echo $file['tmp_name'];
?>
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!希夫

Dar*_*rov 17

基本上我想使用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>
Run Code Online (Sandbox Code Playgroud)

另请注意enctype="multipart/form-data"表格.

另一种可能性是使用HTML5文件API,它允许您实现假设客户端浏览器支持它.


Buz*_*zut 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);
}
Run Code Online (Sandbox Code Playgroud)


odi*_*apc 5

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

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