2016-03-02 130 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)工作