Vanilla JavaScript 및 애니메이션 로딩 PlatoBlockchain Data Intelligence를 사용하여 파일을 업로드합니다. 수직 검색. 일체 포함.

Vanilla JavaScript 및 로딩 애니메이션으로 파일 업로드

파일 업로드는 모든 웹 애플리케이션에서 매우 보편적이며 인터넷(브라우저)을 통해 파일 및 리소스를 업로드할 때 다소 스트레스가 될 수 있습니다. 다행스럽게도 HTML 5에서는 일반적으로 사용자가 데이터를 수정할 수 있도록 양식 컨트롤과 함께 제공되는 입력 요소가 리소스 업로드를 단순화하는 데 매우 편리해졌습니다.

이 기사에서는 바닐라 JavaScript를 사용하여 파일 업로드를 처리하는 방법을 자세히 살펴보겠습니다. 목표는 외부 라이브러리 없이 파일 업로드 구성 요소를 빌드하는 방법을 가르치고 JavaScript의 몇 가지 핵심 개념을 배우는 것입니다. 또한 업로드 진행 상태를 표시하는 방법도 배웁니다.

시작합시다, 여러분!

프로젝트 설정

가장 먼저 원하는 디렉토리에 프로젝트를 위한 새 폴더를 만듭니다.

$ mkdir file-upload-progress-bar-javascript

그렇게 한 후에 이제 생성합시다. index.html, main.cssapp.js 프로젝트의 모든 마크업을 작성할 파일입니다.

$ touch index.html && touch main.css && touch app.js

이제 다음을 사용하여 기본 HTML 템플릿을 만들어 파일 업로드를 위한 구조 구축을 시작할 수 있습니다. 태그 :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>File Upload with Progress Bar using JavaScript</title>
  </head>
  <body></body>
</html>

다음으로 프로젝트의 기본 스타일을 다음 위치에 추가합니다. main.css:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

응용 프로그램의 모양을 향상시키기 위해 공식 font awesome 라이브러리 웹 사이트에서 생성할 수 있는 키트 코드를 통해 프로젝트에 추가할 수 있는 font awesome 라이브러리의 아이콘을 사용할 것입니다.

지금, index.html 업데이트되며, main.css 파일이 링크됨:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script
      src="https://kit.fontawesome.com/355573397a.js"
      crossorigin="anonymous"
    ></script>
    <link rel="stylesheet" href="main.css">
    <title>File Upload with Progress Bar using JavaScript</title>
  </head>
  <body></body>
</html>

계속해서 파일 업로더의 구조를 구축합니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script
      src="https://kit.fontawesome.com/355573397a.js"
      crossorigin="anonymous"
    ></script>
    <link rel="stylesheet" href="main.css" />
    <title>File Upload with Progress Bar using JavaScript</title>
  </head>
  <body>
    <div class="file-upload__wrapper">
      <header>File Uploader JavaScript with Progress</header>
      <div class="form-parent">
        <form action="#" class="file-upload__form">
            <input class="file-input" type="file" name="file" hidden />
            <i class="fas fa-cloud-upload-alt"></i>
            <p>Browse File to Upload</p>
          </form>
          <div>
            <section class="progress-container"></section>
            <section class="uploaded-container"></section>
          </div>
      </div>
    </div>
    <script src="app.js"></script>
  </body>
</html>

그런 다음 다음 코드를 복사/붙여넣기하여 업데이트합니다. main.css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  min-height: 100vh;
  background: #cb67e9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: Arial, Helvetica, sans-serif;
}
::selection {
  color: white;
  background: #cb67e9;
}
.file-upload__wrapper {
  width: 640px;
  background: #fff;
  border-radius: 5px;
  padding: 35px;
  box-shadow: 6px 6px 12px rgba(0, 0, 0, 0.05);
}
.file-upload__wrapper header {
  color: #cb67e9;
  font-size: 2rem;
  text-align: center;
  margin-bottom: 20px;
}
.form-parent {
  display: flex;
  align-items: center;
  gap: 30px;
  justify-content: center;
}
.file-upload__wrapper form.file-upload__form {
  height: 150px;
  border: 2px dashed #cb67e9;
  cursor: pointer;
  margin: 30px 0;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  border-radius: 6px;
  padding: 10px;
}
form.file-upload__form :where(i, p) {
  color: #cb67e9;
}
form.file-upload__form i {
  font-size: 50px;
}
form.file-upload__form p {
  font-size: 1rem;
  margin-top: 15px;
}
section .row {
  background: #e9f0ff;
  margin-bottom: 10px;
  list-style: none;
  padding: 15px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 6px;
}
section .row i {
  font-size: 2rem;
  color: #cb67e9;
}
section .details span {
  font-size: 1rem;
}
.progress-container .row .content-wrapper {
  margin-left: 15px;
  width: 100%;
}
.progress-container .details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 7px;
}
.progress-container .content .progress-bar-wrapper {
  height: 10px;
  width: 100%;
  margin-bottom: 5px;
  background: #fff;
  border-radius: 30px;
}
.content .progress-bar .progress-wrapper {
  height: 100%;
  background: #cb67e9;
  width: 0%;
  border-radius: 6px;
}
.uploaded-container {
  overflow-y: scroll;
  max-height: 230px;
}
.uploaded-container.onprogress {
  max-height: 160px;
}
.uploaded-container .row .content-wrapper {
  display: flex;
  align-items: center;
}
.uploaded-container .row .details-wrapper {
  display: flex;
  flex-direction: column;
  margin-left: 15px;
}
.uploaded-container .row .details-wrapper .name span {
  color: green;
  font-size: 10px;
}
.uploaded-container .row .details-wrapper .file-size {
  color: #404040;
  font-size: 11px;
}

이제 구성요소는 브라우저에서 다음과 같이 표시됩니다.

모범 사례, 업계에서 인정하는 표준 및 포함된 치트 시트가 포함된 Git 학습에 대한 실습 가이드를 확인하십시오. 인터넷 검색 Git 명령을 중지하고 실제로 배움 이것!

프로젝트에 업로드하는 데 필요한 기능을 추가하기 위해 이제 app.js 프로젝트에 생명을 불어넣는 JavaScript 코드를 작성하는 파일입니다.

다음을 복사/붙여넣기 app.js:

const uploadForm = document.querySelector(".file-upload__form");
const myInput = document.querySelector(".file-input");
const progressContainer = document.querySelector(".progress-container");
const uploadedContainer = document.querySelector(".uploaded-container");
uploadForm.addEventListener("click", () => {
  myInput.click();
});
myInput.onchange = ({ target }) => {
  let file = target.files[0];
  if (file) {
    let fileName = file.name;
    if (fileName.length >= 12) {
      let splitName = fileName.split(".");
      fileName = splitName[0].substring(0, 13) + "... ." + splitName[1];
    }
    uploadFile(fileName);
  }
};
function uploadFile(name) {
  let xhrRequest = new XMLHttpRequest();
  const endpoint = "uploadFile.php";
  xhrRequest.open("POST", endpoint);
  xhrRequest.upload.addEventListener("progress", ({ loaded, total }) => {
    let fileLoaded = Math.floor((loaded / total) * 100);
    let fileTotal = Math.floor(total / 1000);
    let fileSize;
    fileTotal < 1024
      ? (fileSize = fileTotal + " KB")
      : (fileSize = (loaded / (1024 * 1024)).toFixed(2) + " MB");
    let progressMarkup = `
  • ${name} | Uploading ${fileLoaded}%
    <div class="progress-wrapper" style="width: ${fileLoaded}%">
  • `
    ; uploadedContainer.classList.add("onprogress"); progressContainer.innerHTML = progressMarkup; if (loaded == total) { progressContainer.innerHTML = ""; let uploadedMarkup = `
  • ${name} | Uploaded ${fileSize}
  • `
    ; uploadedContainer.classList.remove("onprogress"); uploadedContainer.insertAdjacentHTML("afterbegin", uploadedMarkup); } }); let data = new FormData(uploadForm); xhrRequest.send(data); }

    우리가 한 것은 파일 입력 요소를 사용하여 선택된 파일을 읽고 DOM에 새 파일 목록을 생성할 수 있도록 하는 것입니다. 파일 업로드 중이면 진행 상태가 표시되며 파일 업로드가 완료되면 진행 상태가 업로드됨으로 변경됩니다.

    그런 다음 uploadFile.php 파일 전송을 위한 끝점을 모의하기 위해 프로젝트에 추가합니다. 그 이유는 진행률 로딩 효과를 얻을 수 있도록 프로젝트에서 비동기성을 시뮬레이션하기 위해서입니다.

    <?php
      $file_name =  $_FILES['file']['name'];
      $tmp_name = $_FILES['file']['tmp_name'];
      $file_up_name = time().$file_name;
      move_uploaded_file($tmp_name, "files/".$file_up_name);
    ?>
    

    Vanilla JavaScript 및 애니메이션 로딩 PlatoBlockchain Data Intelligence를 사용하여 파일을 업로드합니다. 수직 검색. 일체 포함.

    결론

    이 기사의 이 지점까지 도달하기 위해 정말 수고하셨습니다.

    이 자습서에서는 파일 업로드 구성 요소를 빌드하고 진행률 표시줄을 추가하는 방법을 배웠습니다. 이는 웹 사이트를 구축하고 사용자가 소속감을 느끼고 파일 업로드가 얼마나 느리거나 빠른지 파악하기를 원할 때 유용할 수 있습니다. 원하는 경우 이 프로젝트를 자유롭게 재사용하십시오.

    이 튜토리얼을 따라가는 동안 막히면 GitHub에 프로젝트를 업로드하여 다른 개발자의 도움을 받거나 DM을 보낼 수도 있습니다.

    여기에 링크입니다 프로젝트에 대한 GitHub 저장소.

    관련 리소스

    타임 스탬프 :

    더보기 스택카부스