编程知识 cdmana.com

Ten useful HTML file upload skills for web developers

author : Tapas Adhikary
translator : The front end little wisdom
source :dev
Enjoy it , Develop habits

this paper GitHub https://github.com/qq44924588... I have included , More categories of previous high praise articles , I've also compiled a lot of my documents , And tutorial materials . welcome Star And perfection , You can refer to the interview site review , I hope we have something .

double 11, Big money to buy server front end , Cloud server new users 85 block , Buy through this link to find me cash back 50 block , Equal to you 35 You can buy thousands of configurations in a year .

brief introduction

The upload file function can be said to be a frequent requirement of the project . From uploading photos on social media to posting resumes on job sites , File uploads are everywhere . In this paper , We will discuss HTML File upload supports 10 Usage , I hope it works for you .

1. Single file upload

We can input The type is specified as file, In the Web The file upload function is used in the application .

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

input filte Provide buttons to upload one or more files . By default , It uses the operating system's native file browser to upload a single file . After successful upload ,File API Make it easy to use JS The code is read File object . To read File object , We need to monitor change event .

First , adopt id Get an instance of file upload :

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

And then add a change Event Listener , After the object is uploaded, the file is finished , We from event.target.files Property to get the uploaded file information :

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

Observe the output in the console , Pay attention to FileList Array and File object , This object has all metadata information about the uploaded file .

clipboard.png

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

2. Multiple file upload

If we want to upload multiple files , You need to add multiple attribute :

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

Now? , We can upload multiple files , Based on the previous example , After selecting multiple files to upload , Watch the console change :

clipboard.png

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

3. Understanding file metadata

Every time we upload a file ,File Objects have metadata information , for example file name,size,last update time,type wait . This information is useful for further validation and special processing .

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

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

  //  Get and traverse the 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 output of the upload is a single file :

clipboard.png

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

4. understand accept attribute

We can use accept Property to limit the type of file to upload , If you only want to upload the file format is .jpg,.png when , You can do that :

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

In the code above , You can only choose the suffix is .jpg and .png The file of .

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

5. Manage file content

After successfully uploading the file, the content of the file will be displayed , From the user's point of view , If after uploading , There's no preview of , It's strange and thoughtless .

We can use FileReader Object to convert a file into a binary string . Then add load Event Listener , To get the binary string when the file is successfully uploaded .

// FileReader  example 
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 see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

6. Verify file size

If the user uploads an image that is too large , In order not to put pressure on the server , We need to limit the size of the picture , The following is to allow users to upload less than 1M Pictures of the , If it is greater than 1M Failed to upload .

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

  let msg = '';

 //  Check that 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 see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

7. Show file upload progress

A better user experience is to let users know the progress of file upload , We used it earlier FileReader And read and load file Events .

const reader = new FileReader();

FileReader One more progress event , Indicates the current upload progress , coordination HTML5 Of progress label , Let's simulate the file upload progress .

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

clipboard.png

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

8. How to upload directory upload ?

Can we upload the entire catalog ? Um. , It's possible , But there are some limitations . There's one called webkitdirectory The nonstandard properties of ( At present, only Google browser has Microsoft Edge Support upload by folder ), It allows us to upload the entire catalog .

At present, only Google browser has Microsoft Edge Support upload by folder , Specific can see Baidu cloud disk page version of the upload button , In Firefox, it supports uploading according to the file , And at Google and Edge Next , A drop-down will be provided to the user , Let the user choose whether to upload according to the file or according to the folder .
<input type="file" id="file-uploader" webkitdirectory />

Users need to confirm to upload the directory

clipboard.png

The user clicks “ Upload ” After button , It will upload . Here's an important point to note . FileList The array will contain information about all files in the upload directory in a flat structure . For each File object ,webkitRelativePath Property represents the directory path .

for example , Upload a home directory and other folders and files under it :

clipboard.png

Now? ,File The object will be webkitRelativePath Fill in with :

clipboard.png

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

9. Drag and drop upload

The drag and drop of file upload is not supported low 了 , isn't it? ? Let's see how to do this in a few simple steps .

First , Create a drag and drop area and an optional area to display the contents of the uploaded file .

<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>

Through their respective ID obtain dropzone and content Area .

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

Add one dragover Event handler , To show the effect of the content to be copied :

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

clipboard.png

Next , We need a drop Event listener to handle .

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


});

If you see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

10. Use objectURL Processing documents

There is a special method called URL.createobjecturl(), Used to create unique URL. You can also use URL.revokeObjectURL() Method to release it .

URL.revokeObjectURL() Static methods are used to release a previously existing 、 By calling URL.createObjectURL() Created URL object . When you end up using a URL After object , You should call this method to let the browser know that you don't need to keep the reference to this 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 see this , A little excited , I want to lower my hand , Sure CodePen play , Address :https://codepen.io/atapas/pen...

summary

No matter when , If you want to learn more about this article , You can try it here .

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


Possible after code deployment BUG There's no way to know in real time , In order to solve these problems afterwards BUG, It took a lot of time log debugging , This way, I'd like to recommend an easy-to-use one for you BUG Monitoring tools Fundebug.

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

communication

Articles are updated every week , You can search by wechat 「 The big move the world 」 First time reading and urging ( One or two articles earlier than blog ), this paper GitHub https://github.com/qq449245884/xiaozhi Included , I organized a lot of my documents , welcome Star And perfection , You can refer to the interview site review , Pay attention to official account. , The background to reply welfare , You can see the benefits , You'll see .

版权声明
本文为[Front end intelligence]所创,转载请带上原文链接,感谢

Scroll to Top