2016-11-25 94 views
0

我想用最基本的方法制作一個像圖片上傳器的Facebook。我在輸入上選擇多個圖像,然後創建帶有名稱的每個文件進度條。它顯示它正在加載,但不會發送到upload.php文件。我有HTML代碼部分:

<div class="container"> 
    <h1>Uploader</h1> 
    <hr> 
    <form action="#" id="image_form"> 
     <input type="file" id='image' name="image" multiple> 
    </form> 
    <div class="container"> 
     <div class="filelist"> 
    </div> 
    <ul id="uploads"> 
    </ul> 
</div> 

然後我有我的javascript。進度條使用文件名創建並跟蹤進度。我已經用大文件嘗試過了,上傳需要很長時間。進度條顯示此準確。

$('#image').change(function (event) { 
    var files = this.files; 

    // iterate over each file to upload, send a request, and attach progress event 
    for (var i = 0, file; file = files[i]; i++) { 
     var li = $("<li>" + file.name + "<div class='progress progress-striped active'><div class='progress-bar' style='width:0%'>" + file.size + "</div></div></li>"); 

     // add the LI to the list of uploading files 
     $("#uploads").append(li); 

     // fade in the LI instead of just showing it 
     li.hide().fadeIn(); 

     var xhr = new XMLHttpRequest(); 
     xhr.upload.li = li; 
     xhr.upload.addEventListener('progress', function(e) { 
      var percent = parseInt(e.loaded/e.total * 100); 
      this.li.find(".progress-bar").width(percent+'%'); 
     }, false); 

     // setup and send the file 
     xhr.open('POST', 'upload.php', true); 
     xhr.setRequestHeader('X-FILE-NAME', file.name); 
     xhr.send(file); 
    } 
}); 

我一直在努力與這段代碼的最後一個星期,並已通過幾乎每一個話題在這個網站沒有成功。請有人可以幫我弄清楚爲什麼我不能將文件詳細信息發佈到php腳本。

+0

你怎麼知道它沒有發送? – user2085143

回答

0

我使用此代碼文件發佈到PHP:

function postFile(action, file, postFileName) { 

    var fPostName = typeof postFileName === 'undefined' ? 'file' : postFileName; 
    /* Create a FormData instance */ 
    var formData = new FormData(); 
    /* Add the file */ 
    formData.append(fPostName, file); 

    var requestUrl = rootUrl + action; 

    return new Promise(function (resolve, reject) { 
     var xhr = new XMLHttpRequest(); 
     xhr.open('POST', requestUrl); 

     /* handlers */ 
     xhr.onload = function() { 
      if (this.status >= 200 && this.status < 300) { 
       resolve(xhr.response); 
      } else { 
       reject({ 
        status: this.status, 
        statusText: xhr.statusText 
       }); 
      } 
     }; 
     xhr.onerror = function() { 
      reject({ 
       status: this.status, 
       statusText: xhr.statusText 
      }); 
     }; 

     console.log(formData); 
     /* send request */ 
     xhr.send(formData); 
    }); 
    } 

// Sample usage 
* <<< FILE upload >>>>>> 
* var file = document.getElementById('f').files[0]; 
* console.log(file); 
* postFile('your_processing_script.php', file).then(function (response) { 
*  console.log(response); 
* },function (er) { 
*  console.log(er); 
* }); 

,然後在PHP你應該有:

$_FILES["file"] or $_FILES[postFileName] 

希望這有助於你。 乾杯