2011-03-11 46 views
0

这里是我的非工作的尝试:如何使用jQuery的ajax函数与PHP上传文件?

<?php 

$action = $_GET['request']; 

switch($action) { 

    case 'upload-image': 

     $imageFile = $_GET['file']; 

     $name = $_FILES[$imageFile] ['name']; 
     $tmpLocation = $_FILES[$imageFile] ['tmp_name']; 

      $upload = move_uploaded_file($tmpLocation, "files/$name"); 
      echo ($upload) ? $name.' uploaded successfully!' : 'File not uploaded.'; 

    end; 

} 

?> 

我得到没有上传信息文件:

<script> 
    function uploadImageSubmit() { 

     var imageFile = $('.imageFile').val(); 

     $.ajax({ 

      url: 'ajax.php?request=upload-image&file='+imageFile, 
      success: function(output) { 
       alert(output);      
      } 

     }); 

    } 
</script> 

<h2>Upload File</h2> 

<form> 
    <input type="file" class="imageFile" /> 
    <a onClick="uploadImageSubmit()">Upload</a> 
</form> 

的 “ajax.php” 的代码。我认为这是因为即使字符串可以通过url传递,文件路径也不能出于某种原因。但后来我不知道为什么它不起作用。有人可以找出有什么不对吗?

+0

我想阿贾克斯有一些文件上传的问题http://jquery.malsup.com/form/#file-upload – 2011-03-11 06:26:21

回答

0

实际上,HTML5 and the new File API确实支持通过XmlHttpRequest进行上传。它在Firefox 4和Chrome中运行得非常漂亮。

0

XmlHttpRequest不支持上传文件。你需要使用一些隐藏的iframe或Flash解决方案。

0

您不能使用普通的JS/AJAX上传文件。一个已知的技巧是将您的文件发布到隐藏的iframe并更新iframe。