2014-09-04 114 views
-1

所以我有一個輸入文件字段上傳表單上傳圖片到我的服務器,但我需要在同一時間只能發送一個圖像,例如,用戶選擇在同一個文件輸入字段我希望它50張一次發送一個圖像,並且對於每個圖像,Ajax將向服務器發出新的請求。有理解?任何人都知道該怎麼做?Ajax一次上傳一個文件?

我已經看到了一些插件,這樣做,但沒有解決我的問題完全我想知道怎麼做0作爲被選中,並在同一時間向服務器發送一個每個圖像分開。

+0

因此,您可以選擇多個文件與默認文件類型?據我所知,你一次只能選擇一個文件並一次提交這個文件。 – mrmoment 2014-09-04 01:55:25

+0

我想要做這樣的事情,http://hayageek.com/docs/jquery-upload-file.php,但我沒有得到理解它的邏輯和插件這不符合我的需要100 % – 2014-09-04 02:08:02

回答

0

其實默認<input type="file">控制允許一次選擇一個文件,所以你只能一次上傳一個文件。不過,我最近遇到的需求,讓用戶選擇一個文件夾和上傳文件夾中的文件(一個接一個),我找到一個解決方案(抱歉,我沒有保持溶液URL)。這是我做的:

HTML:

<div> 
    <input type="file" id="files" name="files[]" multiple="" webkitdirectory=""> 
    <div> 
     <input type="submit" value="Upload" class="btn btn-warning pull-left" onclick="uploadFiles()"> 
     <small class="pull-left result_text">Choose a file folder which only contains image files.</small> 
     <div class="clearfix"></div> 
    </div> 
    <div id="output"></div> 
</div>  

的Javascript:

<script type="text/javascript"> 
var File_Lists; 
window.onload = function(){ 
    var output = document.getElementById('output'); 

    // Detect when the value of the files input changes. 
    document.getElementById('files').onchange = function(e) { 
     // Retrieve the file list from the input element 
     File_Lists=e.target.files; 
     // Outputs file names to div id "output" 
     output.innerText = ""; 
     var MAX_ROWS=5; 
     var filenum=File_Lists.length; 
     for (i=0; i<Math.min(filenum, MAX_ROWS); i++){ 
      output.innerText = output.innerText + e.target.files[i].webkitRelativePath+"\n"; 
     } 
     if(filenum>MAX_ROWS){ 
      output.innerText = output.innerText + " and other "+(filenum-MAX_ROWS)+" files..."; 
     } 
    } 
} 


function uploadFiles(){ 
    var files=File_Lists; 
    // Create a new HTTP requests, Form data item (data we will send to the server) and an empty string for the file paths. 
    xhr = new XMLHttpRequest(); 
    data = new FormData(); 
    paths = ""; 

    // Set how to handle the response text from the server 
    xhr.onreadystatechange = function(ev){ 
     //handle with server-side responses 
    }; 

    // Loop through the file list 
    for (var i in files){ 
     // Append the current file path to the paths variable (delimited by tripple hash signs - ###) 
     paths += files[i].webkitRelativePath+"###"; 
     // Append current file to our FormData with the index of i 
     data.append(i, files[i]); 
    }; 
    // Append the paths variable to our FormData to be sent to the server 
    // Currently, As far as I know, HTTP requests do not natively carry the path data 
    // So we must add it to the request manually. 
    data.append('paths', paths); 

    // Open and send HHTP requests to upload.php 
    xhr.open('POST', "process_upload_photo.php", true); 
    xhr.send(this.data); 
} 

我使用PHP的服務器端。您可以使用以下代碼獲取文件路徑,並執行與上載單個文件類似的操作。

$paths = explode("###",rtrim($_POST['paths'],"###"));