10 HTML file upload techniques useful to web developers

By Tapas Adhikary
Translator: front end Xiaozhi
Source: dev

Like and watch again to form a habit

This article GitHub https://github.com/qq44924588... It has been included in the, more classification of high praise articles in previous periods, and also sorted out a lot of my documents and tutorial materials. Welcome Star and perfect. You can review with reference to the test site during the interview. I hope we can have something together.

Double 11, send money to buy servers, learn the big front end, and pay 85 yuan for new users of cloud servers, If you buy through this link, you can find me 50 yuan back , equal to 35, you can buy thousands of configurations in a year.

brief introduction

The function of uploading files can be said to be a frequent requirement of the project. From uploading photos on social media to posting resumes on job search websites, file uploads are everywhere. In this article, we will discuss 10 usages of HTML file upload support, hoping to be useful to you.

1. Single file upload

We can specify the input type as file to use the file upload function in the Web application.

<input type="file" id="file-uploader">

Input filter provides buttons to upload one or more files. By default, it uploads a single File using the operating system's native File browser. After successful upload, the File API enables you to read the File object using simple JS code. To read the File object, we need to listen for the change event.

First, get the file upload instance through id:

const fileUploader = document.getElementById('file-uploader');

Then add a change event listener to read the file object after the upload is completed. We start from event target. The files attribute obtains the uploaded file information:

fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  console.log('files', files);
});

Observe the output results in the console. Here, focus on the FileList array and File object, which has all metadata information about the uploaded File.

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

2. Multi file upload

If we want to upload multiple files, we need to add multiple attribute on the tag:

<input type="file" id="file-uploader" multiple />

Now, we can upload multiple files. Based on the previous examples, select multiple files to upload and observe the changes of the console:

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

3. Understand file metadata

Whenever we upload a File, the File object has metadata information, such as file name, size, last update time, type, and so on. This information is very useful for further verification and special processing.

const fileUploader = document.getElementById('file-uploader');

// Listen to the change file and read the metadata
fileUploader.addEventListener('change', (event) => {
  // Get file list array
  const files = event.target.files;

  // Traverse and get metadata
  for (const file of files) {
    const name = file.name;
    const type = file.type ? file.type: 'NA';
    const size = file.size;
    const lastModified = file.lastModified;
    console.log({ file, name, type, size, lastModified });
  }
});

The following is the output result of single file upload:

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

4. Understand the accept attribute

We can use the accept attribute to limit the type of file to be uploaded. If only the file format to be uploaded is jpg,. png, you can do this:

<input type="file" id="file-uploader" accept=".jpg, .png" multiple>

In the above code, you can only choose the suffix yes jpg and png file.

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

5. Contents of management documents

After uploading the file successfully, the content of the file will be displayed. From the perspective of users, if there is no preview after uploading, it is very strange and considerate.

We can use the FileReader object to convert files to binary strings. Then add a load event listener to get the binary string when the file is uploaded successfully.

// FileReader instance
const reader = new FileReader();

fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  const file = files[0];

  reader.readAsDataURL(file);

  reader.addEventListener('load', (event) => {
    const img = document.createElement('img');
    imageGrid.appendChild(img);
    img.src = event.target.result;
    img.alt = file.name;
  });
});

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

6. Verify file size

If the image uploaded by the user is too large, in order not to put pressure on the server, we need to limit the size of the image. The following is to allow the user to upload an image less than 1M. If it is greater than 1M, the upload will fail.

fileUploader.addEventListener('change', (event) => {
  // Read the file size
  const file = event.target.files[0];
  const size = file.size;

  let msg = '';

 // Check whether the file size is greater than 1MB
  if (size > 1024 * 1024) {
      msg = `<span style="color:red;">The allowed file size is 1MB. The file you are trying to upload is of ${returnFileSize(size)}</span>`;
  } else {
      msg = `<span style="color:green;"> A ${returnFileSize(size)} file has been uploaded successfully. </span>`;
  }
  feedback.innerHTML = msg;
});

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

7. Display file upload progress

A better user experience is to let users know the file upload progress. We used FileReader and the events of reading and loading files earlier.

const reader = new FileReader();

FileReader also has a progress event, which indicates the current upload progress. With the progress tag of HTML5, let's simulate the file upload progress.

reader.addEventListener('progress', (event) => {
  if (event.loaded && event.total) {
    // Calculate percent complete
    const percent = (event.loaded / event.total) * 100;
    // Bind value to 'progress' label
    progress.value = percent;
  }
});

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

8. How to upload the directory?

Can we upload the whole directory? Well, it's possible, but there are some limitations. There is a non-standard attribute called WebKit directory (currently only Google browser and Microsoft Edge support uploading by folder), which allows us to upload the entire directory.

At present, only Google browser and Microsoft Edge support uploading according to folders. For details, you can see the upload button in the web version of Baidu cloud disk. It supports uploading according to files under Firefox, while under Google and Edge, it will provide users with a drop-down to choose whether to upload according to files or folders.

<input type="file" id="file-uploader" webkitdirectory />

The user must confirm to upload the directory

After the user clicks the "Upload" button, it will be uploaded. Here is an important point to pay attention to. The FileList array will contain information about all files in the uploaded directory in a flat structure. For each File object, the webkitRelativePath property indicates the directory path.

For example, upload a home directory and other folders and files under it:

The File object will now populate the webkitRelativePath with:

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

9. Drag upload

Drag and drop that doesn't support file upload is a little low, isn't it? Let's see how this can be achieved in a few simple steps.

First, create a drag and drop area and an optional area to display the uploaded file content.

<div id="container">
  <h1>Drag & Drop an Image</h1>
  <div id="drop-zone">
    DROP HERE
  </div>

  <div id="content">
    Your image to appear here..
  </div>

</div>

Get the dropzone and content area through their respective ID s.

 const dropZone = document.getElementById('drop-zone');
 const content = document.getElementById('content');

Add a dragover event handler to show the effect of what will be copied:

dropZone.addEventListener('dragover', event => {
  event.stopPropagation();
  event.preventDefault();
  event.dataTransfer.dropEffect = 'copy';
});

Next, we need a drop event listener to handle it.

dropZone.addEventListener('drop', event => {
  // Get the files
  const files = event.dataTransfer.files;


});

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

10. Use objectURL to process files

There is a special method called URL Createobjecturl() is used to create a unique URL from the file. You can also use the URL Revokeobjecturl () method to release it.

URL. The revokeobjecturl () static method is used to release a previously existing URL by calling The URL object created by createobjecturl(). When you end using a URL object, you should call this method to let the browser know that you don't need to keep the reference to the file in memory.

fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  const file = files[0];
  
  const img = document.createElement('img');
  imageGrid.appendChild(img);
  img.src = URL.createObjectURL(file);
  img.alt = file.name;
});

If you are a little excited and want to be cheap, you can play with CodePen, address: https://codepen.io/atapas/pen...

summary

Whenever you want to learn more about this article, you can try it here.

https://html-file-upload.netl...

The bugs that may exist after the code is deployed cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

Original text: https://dev.to/atapas/10-usef...

communication

The article is continuously updated every week. You can search "Daqian world" on wechat to read and urge more for the first time (one or two articles earlier than the blog). This article GitHub https://github.com/qq449245884/xiaozhi It has been collected and sorted out many of my documents. Welcome to Star and improve it. You can refer to the examination center for review during the interview. In addition, you can pay attention to the official account. You can see the benefits by replying to the benefits in the background. You know.

Tags: Javascript Front-end html

Posted by tstout2 on Sun, 08 May 2022 10:33:04 +0300