Ten useful HTML file upload skills for web developers

Front end intelligence 2020-11-11 08:31:13
useful html file upload skills


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]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple