2012-08-02 122 views
1

我想使用ajax和php实现文件上传。我有一个表单输入标签。我想要输入标签的onchange事件,文件将被上传到服务器,并且我将在javascript中获取文件的路径!所以,我想保持在同一页面并上传文件,在JavaScript变量中获取文件路径。使用ajax和php上传文件

任何伪代码,示例或教程将不胜感激。

+1

你有什么迄今所做? – 2012-08-02 11:20:52

+0

我已经使用php上传了该文件。但它进入了PHP页面。我想将它保留在同一页面上。 – MJQ 2012-08-02 11:22:06

回答

5

演示网址: -

http://jquery.malsup.com/form/progress.html

你可以从这个网址下载jQuery的文件,并添加in html <head>标签

http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js

http://malsup.github.com/jquery.form.js

试试这个:

这是我的HTML标记:

<!doctype html> 
<head> 
<title>File Upload Progress Demo #1</title> 
<style> 
body { padding: 30px } 
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px } 

.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; } 
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; } 
.percent { position:absolute; display:inline-block; top:3px; left:48%; } 
</style> 
</head> 
<body> 
    <h1>File Upload Progress Demo #1</h1> 
    <code>&lt;input type="file" name="myfile"></code> 
     <form action="upload.php" method="post" enctype="multipart/form-data"> 
     <input type="file" name="uploadedfile"><br> 
     <input type="submit" value="Upload File to Server"> 
    </form> 

    <div class="progress"> 
     <div class="bar"></div > 
     <div class="percent">0%</div > 
    </div> 

    <div id="status"></div> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 
<script> 
(function() { 

var bar = $('.bar'); 
var percent = $('.percent'); 
var status = $('#status'); 

$('form').ajaxForm({ 
    beforeSend: function() { 
     status.empty(); 
     var percentVal = '0%'; 
     bar.width(percentVal) 
     percent.html(percentVal); 
    }, 
    uploadProgress: function(event, position, total, percentComplete) { 
     var percentVal = percentComplete + '%'; 
     bar.width(percentVal) 
     percent.html(percentVal); 
    }, 
    complete: function(xhr) { 
    bar.width("100%"); 
    percent.html("100%"); 
     status.html(xhr.responseText); 
    } 
}); 

})();  
</script> 

</body> 
</html> 

我的PHP代码:

<?php 
$target_path = "uploads/"; 

$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedfile']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 
?> 
+0

感谢您的最佳代码:) – MJQ 2012-08-03 13:13:53

+0

我爱这个谢谢你。有太多的人试图让事情做各种不必要的事情。这很简单,谢谢你! – 2013-09-16 18:58:01

1

这是一种方式,以及如何我做到了。与XHR合作。我有它运行起来,因为我们说话

Using HTML5 file uploads with AJAX and jQuery

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface

$(':file').change(function(){ 
      var file = this.files[0]; 
      name = file.name; 
      size = file.size; 
      type = file.type; 

      if(file.name.length < 1) { 

      } 
      else if(file.size > 100000) { 
       alert("File is to big"); 
      } 
      else if(file.type != 'image/png' && file.type != 'image/jpg' && !file.type != 'image/gif' && file.type != 'image/jpeg') { 
       alert("File doesnt match png, jpg or gif"); 
      } 
      else { 
       $(':submit').click(function(){ 
        var formData = new FormData($('*formId*')[0]); 
        $.ajax({ 
         url: 'script', //server script to process data 
         type: 'POST', 
         xhr: function() { // custom xhr 
          myXhr = $.ajaxSettings.xhr(); 
          if(myXhr.upload){ // if upload property exists 
           myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // progressbar 
          } 
          return myXhr; 
         }, 
         //Ajax events 
         success: completeHandler = function(data) { 
          /* 
          * workaround for crome browser // delete the fakepath 
          */ 
          if(navigator.userAgent.indexOf('Chrome')) { 
           var catchFile = $(":file").val().replace(/C:\\fakepath\\/i, ''); 
          } 
          else { 
           var catchFile = $(":file").val(); 
          } 
          var writeFile = $(":file"); 

          writeFile.html(writer(catchFile)); 

          $("*setIdOfImageInHiddenInput*").val(data.logo_id); 

         }, 
         error: errorHandler = function() { 
          alert("Något gick fel"); 
         }, 
         // Form data 
         data: formData, 
         //Options to tell JQuery not to process data or worry about content-type 
         cache: false, 
         contentType: false, 
         processData: false 
        }, 'json'); 
       }); 
      } 
    });