2012-04-21 105 views
2

上传文件我希望在用户在输入文件中用$ .ajax选择一个文件时异步上传文件。但是,调用返回索引的php未定义。 jQuery代码是下一个:

$("#urlimatge").change(function(){ 
      var filename = $("#urlimatge").val(); 
      $.ajax({ 
       type: "POST", 
       url: "utils/uploadtempimg.php", 
       enctype: 'multipart/form-data', 
       data: {'urlimatge' : filename }, 
       success: function(response){ 
        alert(response); 
       } 
      }); 

     }); 

和recibe呼叫的PHP:

$image = new gestorimatges(); 
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']); 

感谢

回答

1

你不能用AJAX上传文件,但您可以使用一个iframe,所以你不必刷新当前页面。

很多人都喜欢插件,但你可以很容易地做到这一点,并具备AJAX请求的所有功能。

而不是使用AJAX功能的,有一个表单提交到一个隐藏iframe具有附加给它一个load事件处理程序,以便提交表单的时候,你有,实际上包括服务器响应(的HTML的回调函数加载后iframe)。

例子:

HTML -

<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" > 
    <input type="file" name="file" /> 
    <input type="submit" /> 
</form> 
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe> 

JS -

$(function() { 
    $('form').on('submit', function() { 
     //check if the form submission is valid, if so just let it submit 
     //otherwise you could call `return false;` to stop the submission 
    }); 

    $('#workFrame').on('load', function() { 

     //get the response from the server 
     var response = $(this).contents().find('body').html(); 

     //you can now access the server response in the `response` variable 
     //this is the same as the success callback for a jQuery AJAX request 
    }); 
}); 
+0

谢谢我对iframe使用了类似的解决方案。我调用iframe并使用jquery修改action的值。 – 2012-04-21 23:07:55

+0

以下不适用于我:我正在使用多文件上传器来选择多个文件。文件仅通过表单发送。它现在在我的Firefox浏览器中打开一个新的“标签”.... \t

\t \t \t \t \t
rajeev 2012-12-19 01:16:47

+0