Как передать XML-данные на php-сервер? - PullRequest
0 голосов
/ 01 марта 2019

Пожалуйста, помогите, у меня есть код ниже.Я создаю XML-файл, а затем пытаюсь опубликовать эти данные в своем PHP-файле на сервере, чтобы он мог сохранить файл в каталоге «uploads /», где моя сторонняя программа подберет его и извлечет выбранные данные.

Мой вопрос: как я могу передать данные xmlNew в файл и затем передать этот файл в функцию «загрузки»?

HTML:

//Several fields listed here.....
//Then:

    <form method="post" enctype="multipart/form-data">
            <input type="file" name="files[]" multiple>
            <input type="submit" value="Upload File" name="submit">
        </form>

JS:

$(function () {
  $('#DownloadButton').click(update);
})

var template = [
  '<?xml version="1.0"?>',
  '<unattend xmlns="urn:schemas-microsoft-com:unattend">',
  '<Data>',
  ' <SubmitBy><?SubmitBy?></SubmitBy>',
  ' <Level1><?Level1?></Level1>',
  ' <Level2><?Level2?></Level2>',
  ' <Level3><?Level3?></Level3>',
  ' <Level4><?Level4?></Level4>',
  ' <Title><?Title?></Title>',
  ' <Subject><?Subject?></Subject>',
  ' <Author><?Author?></Author>',
  ' <Keywords1><?Keywords1?></Keywords1>',
  ' <Keywords2><?Keywords2?></Keywords2>',
  ' <Destroy_Date><?Destroy_Date?></Destroy_Date>',
  '</Data>',
  '</unattend>'
].join('\r\n');

function update() {
  var variables = {
    'SubmitBy': $('#SubmitBy').val(),
    'Level1': $('#Level1').val(),
    'Level2': $('#Level2').val(),
    'Level3': $('#Level3').val(),
    'Level4': $('#Level4').val(),
    'Title': $('#Title').val(),
    'Subject': $('#Subject').val(),
    'Author': $('#Author').val(),
    'Keywords1': $('#Keywords1').val(),
    'Keywords2': $('#Keywords2').val(),
    'Destroy_Date': $('#Destroy_Date').val(),
  };

  var newXml = template.replace(/<\?(\w+)\?>/g,
    function(match, name) {
      return variables[name];
    });


  $('#ResultXml').val(newXml);
  $('#DownloadLink')
    .attr('href', 'data:text/xml;base64,' + btoa(newXml))
    .attr('download', 'xml_Export.xml');
  $('#generated').show();
}
if (!window.btoa) {
  btoa = function (input) {
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

    var result = '';
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      result += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4);
    } while (i < input.length);

    return result;
  };
}

PHP:

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['files'])) {
        $errors = [];
        $path = 'uploads/';
        $extensions = ['jpg', 'jpeg', 'png', 'gif', 'xml'];

        $all_files = count($_FILES['files']['tmp_name']);

        for ($i = 0; $i < $all_files; $i++) {  
            $file_name = $_FILES['files']['name'][$i];
            $file_tmp = $_FILES['files']['tmp_name'][$i];
            $file_type = $_FILES['files']['type'][$i];
            $file_size = $_FILES['files']['size'][$i];
            $file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));

            $file = $path . $file_name;

            if (!in_array($file_ext, $extensions)) {
                $errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
            }

            if ($file_size > 2097152) {
                $errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
            }

            if (empty($errors)) {
                move_uploaded_file($file_tmp, $file);
            }
        }

        if ($errors) print_r($errors);
    }
}

Любая помощь будет принята с благодарностью.

Спасибо всем!

1 Ответ

0 голосов
/ 01 марта 2019

Небольшая демонстрация, показывающая, как можно с помощью ajax отправить XML-файл в виде строки на сервер PHP, который будет записывать данные в файл.

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['xml'] ) ){
        $file  = __DIR__ . '/ytm.xml';
        $bytes = file_put_contents( $file, $_POST['xml'] );
        exit( sprintf('%d bytes written to %s',$bytes,realpath($file) ) );
    }
?>
<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>send XML data to server to be written to file</title>
        <script>

            var template = [
              '<?xml version="1.0"?>',
              '<unattend xmlns="urn:schemas-microsoft-com:unattend">',
              '<Data>',
              ' <SubmitBy><?SubmitBy?></SubmitBy>',
              ' <Level1><?Level1?></Level1>',
              ' <Level2><?Level2?></Level2>',
              ' <Level3><?Level3?></Level3>',
              ' <Level4><?Level4?></Level4>',
              ' <Title><?Title?></Title>',
              ' <Subject><?Subject?></Subject>',
              ' <Author><?Author?></Author>',
              ' <Keywords1><?Keywords1?></Keywords1>',
              ' <Keywords2><?Keywords2?></Keywords2>',
              ' <Destroy_Date><?Destroy_Date?></Destroy_Date>',
              '</Data>',
              '</unattend>'
            ].join('\r\n');

            const ajax=function( params ){
                with( new XMLHttpRequest() ){
                    onreadystatechange=function(e){
                        if( this.status==200 && this.readyState==4 ){
                            alert( this.response )
                        }
                    }
                    open( 'POST', location.href, true );
                    setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    send( params );
                }
            }

            document.addEventListener('DOMContentLoaded', ()=>{
                document.querySelector('input[ type="button" ]').addEventListener('click', e=>{
                    let vars={};

                    Array.prototype.slice.call( document.querySelectorAll('form > input[ type="text" ]') ).forEach( field =>{
                        vars[ field.name ]=field.value
                    });

                    let xml=template.replace(/<\?(\w+)\?>/ig, (match,name)=>{
                        return vars[name];
                    });

                    ajax.call( this, 'xml='+xml );
                })
            });
        </script>
    </head>
    <body>
        <form method='post'>
            <input type='text' name='SubmitBy' value='bob' />
            <input type='text' name='Level1' value='alpha' />
            <input type='text' name='Level2' value='bravo' />
            <input type='text' name='Level3' value='charlie' />
            <input type='text' name='Level4' value='delta' />
            <input type='text' name='Title' value="geronimo's revenge" />
            <input type='text' name='Subject' value="why is trump such a twit" />
            <input type='text' name='Author' value='bill shakespeare' />
            <input type='text' name='Keywords1' value='love,death,taxes' />
            <input type='text' name='Keywords2' value='cat,dog,fox' />
            <input type='text' name='Destroy_Date' value="2019-03-01" />

            <input type='button' value='Send the XML' />
        </form>
    </body>
</html>
...