Home >Web Front-end >HTML Tutorial >How to upload files? 10 tips for sharing HTML file uploads

How to upload files? 10 tips for sharing HTML file uploads

青灯夜游
青灯夜游forward
2021-12-13 10:38:4718559browse

How to upload files? The following article will share with you 10 tips for uploading HTML files and 10 supported ways of uploading HTML files. I hope it will be helpful to you!

How to upload files? 10 tips for sharing HTML file uploads

The function of uploading files can be said to be a frequent requirement in projects. From uploading photos on social media to posting resumes on job boards, file uploads are everywhere. In this article, we will discuss 10 uses of HTML file upload support, hope it will be useful to you.

1. Single file upload

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

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

input filte Provides buttons to upload one or more files. By default, it uses the operating system's native file browser to upload a single file. After a successful upload, the File API makes it possible to read the File object using simple JS code. To read the File object, we need to listen to the change event.

First, get the instance of the file upload by id:

const fileUploader = document.getElementById(&#39;file-uploader&#39;);

Then add a change event listener to read when the upload is complete To get the file object, we get the uploaded file information from the event.target.files property:

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

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

How to upload files? 10 tips for sharing HTML file uploads

If you are a little excited after seeing this and want to play a little bit, you can play with CodePen, address: https://codepen.io/atapas/pen /rNLOyRm

2. Multiple file upload

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

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

Now, we can upload multiple files. Based on the previous example, after selecting multiple files to upload, observe the changes in the console:

How to upload files? 10 tips for sharing HTML file uploads

If Everyone is a little excited when they see this. If you want to have fun, you can play with CodePen. Address: https://codepen.io/atapas/pen/MWeamYp

3. Understand file metadata

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

const fileUploader = document.getElementById(&#39;file-uploader&#39;);

// 听更 change 件并读取元数据
fileUploader.addEventListener('change', (event) => {
  // 获取文件列表数组
  const files = event.target.files;

  // 遍历并获取元数据
  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 a single file upload:

How to upload files? 10 tips for sharing HTML file uploads

#If you are a little excited after seeing this and want to do something a little trick, you can use CodePen Have fun, address: https://codepen.io/atapas/pen/gOMaRJv

4. Understand the accept attribute

we can use accept attribute to limit the type of files to be uploaded. If you only want to upload the file formats .jpg, .png, you can do this:

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

In the above code, only files with the suffix .jpg and .png can be selected.

If you are a little excited after seeing this and want to play a little bit, you can play with CodePen, address: https://codepen.io/atapas/pen/OJXymRP

5. Manage file content

Display the file content after successfully uploading the file. From the user's perspective, it would be strange and inconsiderate if there is no preview after uploading.

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

// FileReader 实例
const reader = new FileReader();

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

  reader.readAsDataURL(file);

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

If you are a little excited after seeing this and want to play a little bit, you can play with CodePen, address: https://codepen.io/atapas/pen/zYBvdjZ

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 users to upload images smaller than 1M , if it is larger than 1M, the upload will fail.

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

  let msg = &#39;&#39;;

 // 检查文件大小是否大于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 after seeing this and want to play a little bit, you can play with CodePen, address: https://codepen.io/atapas/pen/pobjMKv

7. Display file upload progress

A better user experience is to let the user know the file upload progress. Earlier we used FileReader and events for reading and loading files.

const reader = new FileReader();

FileReaderThere is also a progress event, which indicates the current upload progress. With the progress tag of HTML5, let’s simulate the upload of a file. schedule.

reader.addEventListener(&#39;progress&#39;, (event) => {
  if (event.loaded && event.total) {
    // 计算完成百分比
    const percent = (event.loaded / event.total) * 100;
    // 将值绑定到 `progress`标签
    progress.value = percent;
  }
});

How to upload files? 10 tips for sharing HTML file uploads

如果大家看到这里,有点激动,想手贱一下,可以 CodePen 玩玩,地址:https://codepen.io/atapas/pen/eYzpwYj

8. 怎么上传目录上传?

我们可以上传整个目录吗?嗯,这是可能的,但有一些限制。有一个叫做webkitdirectory的非标准属性(目前只有谷歌浏览器还有Microsoft Edge支持按照文件夹进行上传),它允许我们上传整个目录。

目前只有谷歌浏览器还有Microsoft Edge支持按照文件夹进行上传,具体可以看下百度云盘的网页版的上传按钮,在火狐下就支持按照文件进行上传,而在谷歌和Edge下,就会给用户提供一个下拉,让用户选择是根据文件进行上传还是根据文件夹进行上传。
<input type="file" id="file-uploader" webkitdirectory />

用户必须需要确认才能上传目录

How to upload files? 10 tips for sharing HTML file uploads

用户单击“上传”按钮后,就会进行上传。 这里要注意的重要一点。 FileList数组将以平面结构的形式包含有关上载目录中所有文件的信息。 对于每个File对象,webkitRelativePath属性表示目录路径。

例如,上传一个主目录及其下的其他文件夹和文件:

How to upload files? 10 tips for sharing HTML file uploads

现在,File 对象将将webkitRelativePath填充为:

How to upload files? 10 tips for sharing HTML file uploads

如果大家看到这里,有点激动,想手贱一下,可以 CodePen 玩玩,地址:https://codepen.io/atapas/pen/dyXYRKp

9. 拖拽上传

不支持文件上传的拖拽就有点 low 了,不是吗?我们来看看如何通过几个简单的步骤实现这一点。

首先,创建一个拖放区域和一个可选的区域来显示上传的文件内容。

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

通过它们各自的ID获取dropzonecontent 区域。

 const dropZone = document.getElementById(&#39;drop-zone&#39;);
 const content = document.getElementById(&#39;content&#39;);

添加一个dragover 事件处理程序,以显示将要复制的内容的效果:

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

How to upload files? 10 tips for sharing HTML file uploads

接下来,我们需要一个drop事件监听器来处理。

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

});

如果大家看到这里,有点激动,想手贱一下,可以 CodePen 玩玩,地址:https://codepen.io/atapas/pen/ExyVoXN

10. 使用objectURL处理文件

有一个特殊的方法叫做URL.createobjecturl(),用于从文件中创建唯一的URL。还可以使用URL.revokeObjectURL()方法来释放它。

URL.revokeObjectURL() 静态方法用来释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
fileUploader.addEventListener(&#39;change&#39;, (event) => {
  const files = event.target.files;
  const file = files[0];
  
  const img = document.createElement(&#39;img&#39;);
  imageGrid.appendChild(img);
  img.src = URL.createObjectURL(file);
  img.alt = file.name;
});

如果大家看到这里,有点激动,想手贱一下,可以 CodePen 玩玩,地址:https://codepen.io/atapas/pen/BazzaoN

总结

无论何时,如果你还想学习本文涉及的一些知识,你可以在这里尝试。

英文原文地址:https://dev.to/atapas/10-useful-file-upload-tips-for-web-developers-2d1d

作者: Tapas Adhikary

译者:前端小智

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of How to upload files? 10 tips for sharing HTML file uploads. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to align text in htmlNext article:How to align text in html