Как загрузить файл с помощью javascript?

Я хочу создать загрузчик с js. Может ли кто-нибудь помочь мне, как загрузить файл с помощью javascript?


person Manjeet Kumar Nai    schedule 26.06.2018    source источник
comment
Мы не можем помочь вам до тех пор, пока вы сами себе не поможете. Опубликуйте код, который вы пробовали.   -  person Krishna Prashatt    schedule 26.06.2018
comment
возможно дублировать в stackoverflow.com/questions/5587973/javascript-upload- файл/   -  person Terry Wei    schedule 26.06.2018
comment
Возможный дубликат JavaScript: загрузить файл   -  person JJJ    schedule 26.06.2018


Ответы (3)


Вы можете использовать тип файла html5 следующим образом:

<input type="file" id="myFile">

Ваш файл будет иметь значение:

var myUploadedFile = document.getElementById("myFile").files[0];

Для получения дополнительной информации см. https://www.w3schools.com/jsref/dom_obj_fileupload.asp.

и см. пример здесь: https://www.script-tutorials.com/pure-html5-file-upload/

person Firemen26    schedule 26.06.2018
comment
Я хочу загрузить файл без использования php. Я просто хочу знать, могу ли я загрузить файл с помощью js? - person Manjeet Kumar Nai; 13.06.2019

Вы можете загружать файлы с помощью XMLHttpRequest и FormData. В приведенном ниже примере показано, как загрузить вновь выбранные файлы.

<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {

  const fd = new FormData();

  // add all selected files
  e.target.files.forEach((file) => {
    fd.append(e.target.name, file, file.name);  
  });

  // create the request
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    if (xhr.status >= 200 && xhr.status < 300) {
        // we done!
    }
  };

  // path to server would be where you'd normally post the form to
  xhr.open('POST', '/path/to/server', true);
  xhr.send(fd);
});
</script>

Отказ от ответственности, я являюсь автором FilePond, и это очень похоже на то, как он выполняет загрузку.

person Rik    schedule 18.12.2018

HTML-часть:

<form enctype = "multipart/form-data" onsubmit="return false;" >
       <input id="file" type="file" name="static_file" />
       <button id="upload-button" onclick="uploadFile(this.form)"> Upload </button>
    </form>

Часть JavaScript:

function uploadFile(form){
     const formData = new FormData(form);
     var oOutput = document.getElementById("static_file_response")
     var oReq = new XMLHttpRequest();
         oReq.open("POST", "upload_static_file", true);
     oReq.onload = function(oEvent) {
         if (oReq.status == 200) {
           oOutput.innerHTML = "Uploaded!";
           console.log(oReq.response)
         } else {
           oOutput.innerHTML = "Error occurred when trying to upload your file.<br \/>";
         }
         };
     oOutput.innerHTML = "Sending file!";
     console.log("Sending file!")
     oReq.send(formData);
    }

В приведенном выше HTML я использую форму для захвата файлов и вызова функции JS при нажатии кнопки. В функции JS я использую XMLHttpRequest для отправки файла.

Подробный пошаговый документ можно найти здесь.

person Kartikeya Rana    schedule 26.05.2021