2 Pluspunkte 0 Minuspunkte

Wie kann ich hier einen Datei Upload hinzufügen?

<div id="form-container">
    <form id="the-form" action="comment.php">
        <ul>
            <li><label>first name:</label> <input name="firstname" type="text" value="Jane" /></li>
            <li><label>last name:</label> <input name="lastname" type="text" value="Doe" /></li>
        </ul>    
        <button type="button" onclick="absenden()">submit</button>
    </form>   
</div>

<script>
function absenden() {
    var form = document.getElementById("the-form");
    var formData = new FormData(form);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "comment.php", true);

    xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 400) {
            // Erfolgreiche Antwort vom Server
            console.log(xhr.responseText);
        }
    };

    xhr.onerror = function () {
        // Es gab einen Fehler bei der Anfrage
        console.error(xhr.statusText);
    };

    xhr.send(formData);
}
</script>
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Füge einfach ein "<input>" Element mit dem Attribut type="file" ein. Dadurch kann der Benutzer eine Datei auswählen. Der "enctype" des Formulars wurde auf "multipart/form-data" geändert, um Datei Uploads zu erlauben.

<div id="form-container">
    <form id="the-form" enctype="multipart/form-data">
        <ul>
            <li><label>first name:</label> <input name="firstname" type="text" value="Jane" /></li>
            <li><label>last name:</label> <input name="lastname" type="text" value="Doe" /></li>
            <li><label>file:</label> <input name="file" type="file" /></li>
        </ul>    
        <button type="button" onclick="absenden()">submit</button>
    </form>   
</div>

<script>
function absenden() {
    var form = document.getElementById("the-form");
    var formData = new FormData(form);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "comment.php", true);

    xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 400) {
            // Erfolgreiche Antwort vom Server
            console.log(xhr.responseText);
        }
    };

    xhr.onerror = function () {
        // Es gab einen Fehler bei der Anfrage
        console.error(xhr.statusText);
    };

    xhr.send(formData);
}
</script>
von (532 Punkte)