How do I upload a file to the server via an input form?

  • 0
    This is my task: upload a file to the site using only JavaScript.
    Input for a file on the site looks like this
    I need to download a .pdf file.
    It is important that I cannot use other languages, and third-party libraries, only js.
    Thank you!
    JavaScript Anonymous, Dec 8, 2020

  • 1 Answers
  • 0
    Sketched out a function for you to send a file:

    function sendFile(file, url) {

    // Создаем форму в конструкторе:
    var formData = new FormData();

    // Добавляем наш файл в форму:
    formData.append('file', file,;

    // Отправляем форму на сервер:

    var xhr = new XMLHttpRequest();'POST', url);

    xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
    alert('Запрос выполнен успешно, ответ сервера: ' + xhr.responseText);
    else {
    alert('При выполнении запроса произошла неизвестная ошибка!');



    P. S. Forgot to finish. You can get a file from the field like this:

    input_file = document.querySelector('input[type="file"]').files[0];

    Well, then stupidly call the function I wrote, where the first argument is the received file, and the second is the address where you need to send this file:

    sendFile(input_file, 'https://адрес_куда_отправить');

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!