X
X
xuxubla2016-02-23 20:03:08
PHP
xuxubla, 2016-02-23 20:03:08

How to implement file upload via form using JS?

There is a scriptthat allows you to work with the infoblock step by step. Everything works great, but I can’t figure out how to add the ability to take data from an attached file.
I added, for example, . By clicking on start, a CHttpRequest is executed. The file is naturally not attached. What do you advise? Below I will attach the code, long, sorry.

<?php
if (isset($_REQUEST['work_start']))
{
  define("NO_AGENT_STATISTIC", true);
  define("NO_KEEP_STATISTIC", true);
}

if($_REQUEST['work_start'] && check_bitrix_sessid())
{
  $rsEl = CIBlockElement::GetList(array("ID" => "ASC"), array("IBLOCK_ID" => $BID, ">ID" => $_REQUEST["lastid"]), false, array("nTopCount" => $limit));
  while ($arEl = $rsEl->Fetch())
  {	/*
     * do something
     */
    $lastID = intval($arEl["ID"]);
  }

  $rsLeftBorder = CIBlockElement::GetList(array("ID" => "ASC"), array("IBLOCK_ID" => $BID, "<=ID" => $lastID));
  $leftBorderCnt = $rsLeftBorder->SelectedRowsCount();

  $rsAll = CIBlockElement::GetList(array("ID" => "ASC"), array("IBLOCK_ID" => $BID));
  $allCnt = $rsAll->SelectedRowsCount();

  $p = round(100*$leftBorderCnt/$allCnt, 2);

  echo 'CurrentStatus = Array('.$p.',"'.($p < 100 ? '&lastid='.$lastID : '').'","Обрабатываю запись с ID #'.$lastID. key($_FILES) .' ");';
  var_dump($_FILES);
  die();
}

$clean_test_table = '<table id="result_table" cellpadding="0" cellspacing="0" border="0" width="100%" class="internal">'.
            '<tr class="heading">'.
              '<td>Текущее действие</td>'.
              '<td width="1%">&nbsp;</td>'.
            '</tr>'.
          '</table>';
$aTabs = array(array("DIV" => "edit1", "TAB" => "Обработка"));
$tabControl = new CAdminTabControl("tabControl", $aTabs);
?>
<script type="text/javascript">
  var bWorkFinished = false;
  var bSubmit;
  function set_start(val)
  {
    document.getElementById('work_start').disabled = val ? 'disabled' : '';
    document.getElementById('work_stop').disabled = val ? '' : 'disabled';
    document.getElementById('progress').style.display = val ? 'block' : 'none';
    if (val)
    {
      ShowWaitWindow();
      document.getElementById('result').innerHTML = '<?=$clean_test_table?>';
      document.getElementById('status').innerHTML = 'Работаю...';
      document.getElementById('percent').innerHTML = '0%';
      document.getElementById('indicator').style.width = '0%';
      CHttpRequest.Action = work_onload;
      CHttpRequest.Send('<?= $_SERVER["PHP_SELF"]?>?work_start=Y&lang=<?=LANGUAGE_ID?>&<?=bitrix_sessid_get()?>');
    }
    else
      CloseWaitWindow();
  }

  function work_onload(result)
  {
    try
    {
      eval(result);

      iPercent = CurrentStatus[0];
      strNextRequest = CurrentStatus[1];
      strCurrentAction = CurrentStatus[2];

      document.getElementById('percent').innerHTML = iPercent + '%';
      document.getElementById('indicator').style.width = iPercent + '%';

      document.getElementById('status').innerHTML = 'Работаю...';

      if (strCurrentAction != 'null')
      {
        oTable = document.getElementById('result_table');
        oRow = oTable.insertRow(-1);
        oCell = oRow.insertCell(-1);
        oCell.innerHTML = strCurrentAction;
        oCell = oRow.insertCell(-1);
        oCell.innerHTML = '';
      }

      if (strNextRequest && document.getElementById('work_start').disabled)
        CHttpRequest.Send('<?= $_SERVER["PHP_SELF"]?>?work_start=Y&lang=<?=LANGUAGE_ID?>&<?=bitrix_sessid_get()?>' + strNextRequest);
      else
      {
        set_start(0);
        bWorkFinished = true;
      }

    }
    catch(e)
    {
      CloseWaitWindow();
      document.getElementById('work_start').disabled = '';
      alert('Сбой в получении данных');
    }
  }

</script>
<p>Форма для обновления информации о товарах</p>
<form method="post" action="<?echo $APPLICATION->GetCurPage()?>" enctype="multipart/form-data" name="post_form" id="post_form">
<?
echo bitrix_sessid_post();

$tabControl->Begin();
$tabControl->BeginNextTab();
?>
  <tr>
    <td colspan="2">
      <input type="file" name="filename" />
      <input type=submit value="Старт" id="work_start" onclick="set_start(1)" />
      <input type=button value="Стоп" disabled id="work_stop" onclick="bSubmit=false;set_start(0)" />
      <div id="progress" style="display:none;" width="100%">
      <br />
        <div id="status"></div>
        <table border="0" cellspacing="0" cellpadding="2" width="100%">
          <tr>
            <td height="10">
              <div style="border:1px solid #B9CBDF">
                <div id="indicator" style="height:10px; width:0%; background-color:#B9CBDF"></div>
              </div>
            </td>
            <td width=30>&nbsp;<span id="percent">0%</span></td>
          </tr>
        </table>
      </div>
      <div id="result" style="padding-top:10px"></div>
    </td>
  </tr>
<?
$tabControl->End();
?>
</form>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-02-23
@bingo347

Look towards FileApi

E
Express777, 2016-02-24
@Express777

Perhaps this will point you in the right direction. This is how I save files via JS.

// Создаем форму на джавскрипте, туда можно запихнуть любой инпут. В нашем случае нужен файл.
var formData = new FormData();
// Берем файл из инпута. Ид инпута id-input-file-2. Здесь легко использовать getElementByID
  var file = $('#id-input-file-2')[0].files[0];
// Добавляем файл
  formData.append("myFileName", file);
// Отправка на сервер. В вашем случае будет на тот же файл.
  // Вариант через Ваниллу
        //var xhr = new XMLHttpRequest();
  //xhr.open("POST", "/upload/save-file/");
  //xhr.send(formData);
  //
  //xhr.onreadystatechange = function() {
  //
  //	if( xhr.readyState == 4 ) {
  //		Если все хорошо .....
  //	}
  //}

  $fileUpload = $.ajax({
    url: "/upload/save-file/",
    data: formData,
    method: 'post',
    processData: false, // Два важных параметра. Без них отправляется не корректно
    contentType: false // Два важных параметра. Без них отправляется не корректно
  });

Receive an array on the server
$_FILES['myFileName']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question