Upload de arquivos com PHP e XMLHttpRequest - método change

index:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Upload XMLHttpRequest</title>
</head>
<body>

    <form method="POST" action="" enctype="multipart/form-data">
        <input id="upload" type="file" accept=".*" name="upload" />
        <label for="upload" class="btn">Escolher Arquivo</label>
    </form>
    <span id="file-type"></span><br />
    <input id="file-url" type="url" name="file-url" /><br />
    <input id="file-dir" type="text" name="file-dir" />
    <div id="callback"></div>

<script src="script.js"></script>
</body>
</html>

 

script.js:

let inputfile = document.querySelector("#upload");
let callback  = document.querySelector("#callback");
let inputurl  = document.querySelector("#file-url");
let inputdir  = document.querySelector("#file-dir");
let inputype  = document.querySelector("#file-type");
inputfile.addEventListener('change', function() {
    var file = this.files[0];
    var upload = new FormData();
    upload.append("upload", file);
    var request = new XMLHttpRequest();
    request.open("POST", "http://localhost/upload-XMLHttpRequest/change/upload.php");
    request.addEventListener('load', function() {
        if(this.status == 200) {
            var result = JSON.parse(this.response);
            inputype.innerHTML = result.type;
            inputurl.value = result.url;
            inputdir.value = result.path;
            callback.innerHTML = '<img src="'+result.url+'" alt="" />';
        }
    });
    request.send(upload);
});

 

upload.php

$filename = $_FILES["upload"]["name"];

$filetype = $_FILES["upload"]["type"];

$path = __DIR__;
$path = str_replace("\\", "/", $path);
$path = $path.'/uploads/';
if(!is_dir($path)) {
    mkdir($path, 0777, true);
}

move_uploaded_file( $_FILES["upload"]["tmp_name"], $path.$filename );

$protocol = isset($_SERVER["HTTPS"]) ? 'https://' : 'http://';
$base = str_replace($_SERVER["DOCUMENT_ROOT"], $_SERVER["SERVER_NAME"], $path);

echo json_encode([
    'path' => $path.$filename,
    'url'  => $protocol.$base.$filename,
    'type' => $filetype 
]);
Categorias: JavaScript, PHP, XMLHttpRequest