duancaozen6066 2016-07-25 23:26
浏览 146
已采纳

使用AJAX上传文件和$ _POST失败

I'm trying to upload a file and some text inside a textarea together using AJAX. I'm getting the following error in the PHP page that receives the data:

Notice: Undefined index: guion in file/path/here on line X

It means that the file is not being sent. Tried var_dump $_FILES and it output:

array(0) { }

HTML Code:

<div id="_AJAX_"></div>

<div role="form">
  <div id="fileGuionGroup" class="form-group">
    <label for="guion">Archivo Gui&oacute;n</label>
    <input id="fileGuion" type="file" name="guion">
  </div>

  <div id="txtComentarioGroup" class="form-group">
    <label for="comentario">Comentario</label>
    <textarea id="txtComentario" class="form-control" name="comentario" rows="4" placeholder="Ejemplo: Solicito que por favor se monte este curso en plataforma."></textarea>
  </div>
</div>

<button id="send_request" type="button" class="btn btn-primary btn-block" onclick="submitSolicitud(`{$cursoKey}`)"><i class="fa fa-fw fa-cogs"></i> Solicitar Montaje</button>

Javascript Code:

function submitSolicitud(cursoKey) {
  var fileGuion     = document.getElementById('fileGuion');
  var txtComentario = document.getElementById('txtComentario');

  var formGroupGuion      = document.getElementById('fileGuionGroup');
  var formGroupComentario = document.getElementById('txtComentarioGroup');

  formGroupGuion.className      = "form-group";
  formGroupComentario.className = "form-group";

  var guion      = fileGuion.value;
  var comentario = txtComentario.value;

  var formData = new FormData();
  formData.append('guion', guion);
  formData.append('comentario', comentario);

  connect = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

  connect.onreadystatechange = function () {
    onRSCallback(cursoKey);
  };

  connect.open('POST', '?view=modalsMatriz&modal=montaje&id=' + cursoKey + '&action=solicitarMontaje', true);
  connect.setRequestHeader("Content-Type", "multipart/form-data");
  connect.setRequestHeader("X-File-Name", guion.name);
  connect.setRequestHeader("X-File-Size", guion.size);
  connect.setRequestHeader("X-File-Type", guion.type);
  connect.send(formData);
};

PHP Code:

case 'solicitarMontaje':

    // This is the line that has the error of undefined index.
  die($_FILES['guion']);

  try {
    if (!isset($_FILES['guion'])) {
        # Code 1: Archivo Guión Field vacía
      throw new Exception(1);
    } elseif (!isset($_POST['comentario']) || $_POST['comentario'] == "") {
        # Code 2: Comentario Field vacío
      throw new Exception(2);
    }

    $tmp_file = $_FILES['guion']['tmp_name'];
    $filename = $_FILES['guion']['name'];

    move_uploaded_file($tmp_file, 'uploads/guiones/'.$filename);

    die(0);
    //$curso->crearSolicitudMontaje($_POST['comentario']);
  } catch (Exception $e) {
      # Output message to the screen so that Ajax captures it via connect.responseText @curso_FormMontaje.js
    echo $e->getMessage();
  }
break;  # ./ case 'solicitarMontaje'

I've tried it using FormData() and Content-Type multipart/form-data but it did not work at all. Instead it was making the page be embedded inside the _AJAX_ div that shows the messages returned from the server (such as success messages, errors at some fields i.e fields that were sent empty).

This is what I get as result using FormData when clicking the submit button:

https://postimg.org/image/rsnrt3yq9/

  • 写回答

2条回答 默认 最新

  • dongwo5686 2016-07-30 14:25
    关注

    Turns out that what was causing issues were the HTTP headers (setRequestHeader). I removed them and edited the code a little bit, here's what it looks like now fully functional:

    JavaScript Code:

    function submitSolicitud(cursoKey) {
      var fileGuion     = document.getElementById('fileGuion');
      var txtComentario = document.getElementById('txtComentario');
    
      var guion      = fileGuion.files[0];
      var comentario = txtComentario.value;
    
      var formData = new FormData();
    
      formData.append('guion', guion);
      formData.append('comentario', comentario);
    
      connect = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    
      connect.onreadystatechange = function () {
        onRSCallback(cursoKey);
      };
    
      connect.open('POST', '?view=modalsMatriz&modal=montaje&id=' + cursoKey + '&action=solicitarMontaje', true);
    
      connect.send(formData);
    };       
    

    As expected, the data is recognized by PHP as below:

    • The file "guion" comes into PHP's $_FILES array ($_FILES['guion']).

    • The "comentario" field (textarea) is sent inside PHP's $_POST array ($_POST['comentario']).

    Finally, both HTML and PHP code stayed the same and the conclusion is that by not setting the HTTP headers they seem to take the proper value automatically so that the request processes correctly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同