2016-03-02 91 views
-1

使用XMLHttpRequest將文件上傳到php腳本。問題是我不能改變客戶端的文件名,我正在努力解決如何發送變量該文件。PHP文件上傳XMLHttpRequest傳遞

我在屏幕上有一個文本框,基本上當用戶提交文件時,我想從文本框中的文本轉到php文件aswel。

這裏是我的上傳功能:

function uploadFile() { 

    var fd = new FormData(); 

      var count = document.getElementById('fileToUpload').files.length; 

      for (var index = 0; index < count; index ++) 

      { 

       var file = document.getElementById('fileToUpload').files[index]; 

       fd.append('myFile', file); 


      } 
    var xhr = new XMLHttpRequest(); 

    xhr.upload.addEventListener("progress", uploadProgress, false); 

    xhr.addEventListener("load", uploadComplete, false); 

    xhr.addEventListener("error", uploadFailed, false); 

    xhr.addEventListener("abort", uploadCanceled, false); 

    xhr.open("POST", "savetofile.php"); 

    xhr.send(fd); 

    } 

,並在php文件:

<?php 
if (isset($_FILES['myFile'])) { 

    // $text = contents of the textbox that has been sent from javascript 

    move_uploaded_file($_FILES['myFile']['tmp_name'], "daa_coke/images/" . $_FILES['myFile']['name']); 
    $xml = simplexml_load_file('daa_coke/newcoke.xml'); 
$employee = $xml->addChild('flight'); 
$employee->addChild('to', 'dsd'); 
$employee->addChild('from', 'Gary'); 
$employee->addChild('imagepath', $_FILES['myFile']['name']); 
$employee->addChild('templateStyle', 'template1'); 
$employee->addChild('time', '13:37'); 
$employee->addChild('date', '24/12/16'); 

file_put_contents('daa_coke/newcoke.xml', $xml->asXML()); 


} 
?> 

我只是希望能夠通過文本框的內容,所以我canput在$測試變量。

+0

剛做了另外追加...'fd.append( 'textBoxName',textBoxValue)' – charlietfl

+0

我曾嘗試這和它不添加任何東西 –

回答

0

filename應傳遞第三個參數爲.append()

formData.append(name, value, filename); 

例如;

fd.append("myFile", file, this.querySelector("input[type=text]").value); 

FormData.append()

0

fd.append( 'textBoxName',textBoxValue)工作