How to Upload File to Web Page

Introduction

The ability to upload files is a key requirement for many web and mobile applications. From uploading your photograph on social media to postal service your resume on a job portal website, file upload is everywhere.

As a web programmer, we must know that HTML provides the back up of native file upload with a bit of help from JavaScript. With HTML5 the File API is added to the DOM. Using that, nosotros can read the FileList and the File Object within it. This solves multiple use-cases with files, i.east, load them locally or transport over the network to a server for processing, etc.

In this article, we will discuss ten such usages of HTML file upload back up. Hope you find it useful.

TL;DR

At any point in time, if yous desire to play with these file upload features, y'all can find it from here,

  • HTML File Upload Demo: https://html-file-upload.netlify.app/

The source code of the demo is in my Github repo. ✋ Feel costless to follow equally I keep the lawmaking updated with examples. Please give a ⭐ if you notice it useful.

  • Source Code Repo: https://github.com/atapas/html-file-upload

1. Elementary file upload

Nosotros tin specify the input blazon as file to use the file uploader functionality in a web application.

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

An input file blazon enables users with a push button to upload i or more files. Past default, it allows uploading a single file using the operating system's native file browser.

On successful upload, the File API makes it possible to read the File object using simple JavaScript code. To read the File object, we need to listen to the change event of the file uploader.

Outset, get the file uploader instance by id,

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

Then add a change event listener to read the file object when the upload completes. We get the uploaded file data from the event.target.files property.

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

Observe the output in the browser console. Notation the FileList array with the File object having all the metadata information well-nigh the uploaded file.

image.png

Here is the CodePen for you lot with the aforementioned example to explore further

two. Multiple file uploads

We can upload multiple files at a fourth dimension. To do that, nosotros simply need to add together an attribute called, multiple to the input file tag.

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

Now, the file browser will allow you lot to upload ane or more files to upload. Only like the previous example, y'all can add a change event handler to capture the data virtually the files uploaded. Have you lot noticed, the FileList is an array? Right, for multiple file uploads the assortment will have information every bit,

image.png

Here is the CodePen link to explore multiple file uploads.

Whenever we upload a file, the File object has the metadata data like file name, size, last update time, type, etc. This information can be useful for further validations, decision-making.

                      // Get the file uploader by id            const            fileUploader =            document.getElementById('file-uploader');            // Listen to the change event and read metadata            fileUploader.addEventListener('change',            (event) =>            {            // Get the FileList array            const            files = event.target.files;            // Loop through the files and get metadata            for            (const            file            of            files) {            const            proper noun = file.name;            const            type = file.type ? file.type:            'NA';            const            size = file.size;            const            lastModified = file.lastModified;            console.log({ file, name, type, size, lastModified });   } });                  

Here is the output for single file upload,

image.png

Use this CodePen to explore further,

4. Know about file accept property

Nosotros can apply the accept aspect to limit the type of files to upload. You may desire to evidence simply the allowed types of images to scan from when a user is uploading a profile pic.

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

In the code in a higher place, the file browser will allow only the files with the extension jpg and png.

Notation, in this case, the file browser automatically sets the file selection type as custom instead of all. Nonetheless, you can always change it dorsum to all files, if required.

image.png

Utilize this CodePen to explore the accept attribute,

5. Manage file content

Y'all may want to bear witness the file content after a successful upload of information technology. For profile pictures, it will exist disruptive if we do not evidence the uploaded picture to the user immediately after upload.

We tin use the FileReader object to convert the file to a binary string. So add a load event listener to get the binary string on successful file upload.

                      // Get the instance of the FileReader            const            reader =            new            FileReader();  fileUploader.addEventListener('alter',            (event) =>            {            const            files = event.target.files;            const            file = files[0];            // Go the file object after upload and read the            // data every bit URL binary cord            reader.readAsDataURL(file);            // Once loaded, practice something with the string            reader.addEventListener('load',            (event) =>            {            // Hither nosotros are creating an image tag and adding            // an image to information technology.            const            img =            document.createElement('img');     imageGrid.appendChild(img);     img.src = effect.target.outcome;     img.alt = file.name;   }); });                  

Try selecting an image file in the CodePen below and see it renders.

6. Validate file size

Equally we have seen, we can read the size metadata of a file, we can actually employ it for a file size validation. You may let users to upload an image file up to 1MB. Allow us see how to achieve that.

                      // Listener for file upload change event            fileUploader.addEventListener('change',            (event) =>            {            // Read the file size            const            file = issue.target.files[0];            const            size = file.size;            allow            msg =            '';            // Bank check if the file size is bigger than 1MB and fix a message.            if            (size >            1024            *            1024) {       msg =            `<span way="colour:red;">The immune file size is 1MB. The file y'all are trying to upload is of              ${returnFileSize(size)}</bridge>`;   }            else            {       msg =            `<span style="color:green;"> A              ${returnFileSize(size)}              file has been uploaded successfully. </bridge>`;   }            // Show the message to the user            feedback.innerHTML = msg; });                  

Effort uploading a file of different sizes to run into how the validation works,

7. Prove file upload progress

The better usability is to allow your users know nearly a file upload progress. We are now enlightened of the FileReader and the event to read and load the file.

                      const            reader =            new            FileReader();                  

The FileReader has another event called, progress to know how much has been loaded. Nosotros tin can use HTML5's progress tag to create a progress bar with this information.

          reader.addEventListener('progress',            (event) =>            {            if            (outcome.loaded && upshot.total) {            // Calculate the percentage completed            const            percent = (event.loaded / event.total) *            100;            // Set up the value to the progress component            progress.value = percent;   } });                  

How virtually you attempt uploading a bigger file and see the progress bar working in the CodePen below? Give it a try.

8. How about directory upload?

Can we upload an entire directory? Well, information technology is possible but with some limitations. There is a non-standard aspect(at least, while writing this article) called, webkitdirectory that allows us to upload an entire directory.

Though originally implemented simply for WebKit-based browsers, webkitdirectory is besides usable in Microsoft Border likewise every bit Firefox 50 and later. Notwithstanding, even though information technology has relatively broad support, it is all the same not standard and should not be used unless y'all have no alternative.

You tin can specify this attribute equally,

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

This will allow yous to select a folder(aka, directory),

image.png

User has to provide a confirmation to upload a directory,

image.png

Once the user clicks the Upload button, the uploading takes place. One important signal to annotation here. The FileList array volition have information about all the files in the uploaded directory every bit a flat structure. Only the key is, for each of the File objects, the webkitRelativePath attribute will take the directory path.

For instance, let united states consider a principal directory and other folders and files nether it,

image.png

At present the File objects will have the webkitRelativePath populated as,

image.png

You can use it to render the binder and files in whatsoever UI structure of your option. Utilize this CodePen to explore further.

9. Permit'southward elevate, drop and upload

Not supporting a elevate-and-drib for file upload is kinda old way, isn't it? Let united states see how to achieve that with a few unproblematic steps.

Start, create a drop zone and optionally a section to evidence the uploaded file content. We will use an image as a file to drag and drop here.

                      <div              id="container">            <h1>Elevate & Drop an Prototype</h1>            <div              id="drib-zone">            DROP HERE            </div>            <div              id="content">            Your image to appear here..            </div>            </div>                  

Become the dropzone and the content areas past their respective ids.

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

Add a dragover event handler to show the effect of something going to be copied,

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

image.png

Side by side, define what we want to do when the image is dropped. Nosotros will demand a drop issue listener to handle that.

          dropZone.addEventListener('drop',                          outcome              =>            {            // Get the files            const            files = result.dataTransfer.files;            // Now we can exercise everything possible to prove the            // file content in an HTML chemical element like, DIV            });                  

Try to drag and driblet an image file in the CodePen instance below and run into how it works. Do not forget to run into the code to render the dropped image as well.

10. Handle files with objectURLs

There is a special method called, URL.createObjectURL() to create an unique URL from the file. Y'all tin can also release it past using URL.revokeObjectURL() method.

The DOM URL.createObjectURL() and URL.revokeObjectURL() methods allow you create elementary URL strings that tin can exist used to reference any data that can be referred to using a DOM File object, including local files on the user's computer.

A unproblematic usage of the object URL is,

          img.src = URL.createObjectURL(file);                  

Use this CodePen to explore the object URL further. Hint: Compare this approach with the approach mentioned in #v previously.

Conclusion

I truly believe this,

Many times a native HTML feature may exist enough for us to deal with the use-cases in hands. I constitute, file upload is 1 such that provides many cool options by default.

Let me know if this article was useful to you by commenting below. You may also like,

  • 10 useful HTML5 features, you may not exist using
  • I fabricated a photo gallery with CSS animation. Hither'south what I learned.
  • ten lesser-known Web APIs you lot may desire to utilise

If information technology was useful to yous, please Similar/Share and so that, it reaches others too. Please hit the Subscribe button at the top of the page to go an email notification on my latest posts.

You can @ me on Twitter (@tapasadhikary) with comments, or feel free to follow me.

regancloquencond.blogspot.com

Source: https://blog.greenroots.info/10-useful-html-file-upload-tips-for-web-developers

0 Response to "How to Upload File to Web Page"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel