Html Choose File and Upload Html Choose Folder and Upload
Introduction
The ability to upload files is a primal requirement for many web and mobile applications. From uploading your photo on social media to post your resume on a chore portal website, file upload is everywhere.
Every bit a web developer, nosotros must know that HTML provides the support of native file upload with a bit of assist from JavaScript. With HTML5 the File API is added to the DOM. Using that, nosotros tin read the FileList and the File Object within it. This solves multiple apply-cases with files, i.e, load them locally or transport over the network to a server for processing, etc.
In this article, nosotros volition discuss 10 such usages of HTML file upload support. Hope you find it useful.
TL;DR
At any indicate in time, if you want to play with these file upload features, yous tin 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 as I go on the code updated with examples. Please requite a ⭐ if you find it useful.
- Source Code Repo: https://github.com/atapas/html-file-upload
i. Simple file upload
We can specify the input blazon equally file to use the file uploader functionality in a spider web application.
<input type="file" id="file-uploader"> An input file type enables users with a push to upload one or more files. Past default, it allows uploading a unmarried file using the operating organization'due south native file browser.
On successful upload, the File API makes information technology possible to read the File object using simple JavaScript code. To read the File object, we need to listen to the alter event of the file uploader.
Commencement, become the file uploader instance by id,
const fileUploader = certificate.getElementById('file-uploader'); And so add a change event listener to read the file object when the upload completes. Nosotros become the uploaded file information from the event.target.files property.
fileUploader.addEventListener('change', (event) => { const files = upshot.target.files; console.log('files', files); }); Notice the output in the browser console. Notation the FileList array with the File object having all the metadata information about the uploaded file.
Here is the CodePen for you with the same example to explore farther
ii. Multiple file uploads
We can upload multiple files at a time. To exercise that, we merely need to add an attribute chosen, multiple to the input file tag.
<input blazon="file" id="file-uploader" multiple /> Now, the file browser will permit you to upload one or more files to upload. Just like the previous example, you can add together a change effect handler to capture the information about the files uploaded. Have you noticed, the FileList is an array? Right, for multiple file uploads the assortment volition have information as,
Here is the CodePen link to explore multiple file uploads.
Whenever we upload a file, the File object has the metadata information like file proper noun, size, last update time, blazon, etc. This information can be useful for further validations, conclusion-making.
// Go the file uploader by id const fileUploader = document.getElementById('file-uploader'); // Listen to the change event and read metadata fileUploader.addEventListener('modify', (event) => { // Get the FileList array const files = upshot.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, blazon, size, lastModified }); } }); Here is the output for single file upload,
Utilize this CodePen to explore further,
4. Know about file take property
We can employ the accept attribute to limit the blazon of files to upload. Yous may want to evidence only the allowed types of images to browse from when a user is uploading a profile motion-picture show.
<input blazon="file" id="file-uploader" accept=".jpg, .png" multiple> In the lawmaking in a higher place, the file browser will allow but the files with the extension jpg and png.
Note, in this example, the file browser automatically sets the file option type every bit custom instead of all. Withal, y'all can e'er change it back to all files, if required.
Apply this CodePen to explore the accept attribute,
5. Manage file content
You may want to evidence the file content after a successful upload of it. For contour pictures, it volition exist confusing if we do not bear witness the uploaded moving picture to the user immediately after upload.
We can apply the FileReader object to convert the file to a binary cord. Then add a load event listener to go the binary string on successful file upload.
// Get the instance of the FileReader const reader = new FileReader(); fileUploader.addEventListener('change', (event) => { const files = event.target.files; const file = files[0]; // Go the file object afterwards upload and read the // information as URL binary cord reader.readAsDataURL(file); // Once loaded, practice something with the string reader.addEventListener('load', (event) => { // Here we are creating an image tag and adding // an prototype to it. const img = document.createElement('img'); imageGrid.appendChild(img); img.src = event.target.result; img.alt = file.name; }); }); Try selecting an image file in the CodePen beneath and see it renders.
half dozen. Validate file size
Every bit we take seen, we can read the size metadata of a file, we can actually employ it for a file size validation. You lot may allow users to upload an image file up to 1MB. Permit us encounter how to reach that.
// Listener for file upload change consequence fileUploader.addEventListener('change', (event) => { // Read the file size const file = event.target.files[0]; const size = file.size; allow msg = ''; // Cheque if the file size is bigger than 1MB and prepare a message. 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:light-green;"> A ${returnFileSize(size)} file has been uploaded successfully. </span>`; } // Show the message to the user feedback.innerHTML = msg; }); Endeavor uploading a file of different sizes to see how the validation works,
7. Show file upload progress
The amend usability is to permit your users know almost a file upload progress. Nosotros 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. We can use HTML5's progress tag to create a progress bar with this information.
reader.addEventListener('progress', (effect) => { if (event.loaded && event.total) { // Summate the percentage completed const percent = (consequence.loaded / result.total) * 100; // Set the value to the progress component progress.value = percent; } }); How about you try uploading a bigger file and see the progress bar working in the CodePen below? Give it a try.
8. How about directory upload?
Tin can nosotros upload an entire directory? Well, it is possible but with some limitations. There is a not-standard aspect(at to the lowest degree, while writing this article) called, webkitdirectory that allows us to upload an unabridged directory.
Though originally implemented only for WebKit-based browsers, webkitdirectory is also usable in Microsoft Edge equally well as Firefox 50 and after. Nonetheless, even though it has relatively broad support, it is still not standard and should not be used unless you take no culling.
You lot tin specify this aspect every bit,
<input type="file" id="file-uploader" webkitdirectory /> This will allow you to select a folder(aka, directory),
User has to provide a confirmation to upload a directory,
Once the user clicks the Upload button, the uploading takes place. One important point to note hither. The FileList array will accept information about all the files in the uploaded directory as a flat structure. But the key is, for each of the File objects, the webkitRelativePath attribute will have the directory path.
For example, let u.s.a. consider a principal directory and other folders and files under it,
Now the File objects will have the webkitRelativePath populated as,
You lot tin utilise it to render the folder and files in any UI structure of your choice. Use this CodePen to explore further.
9. Let'south elevate, drop and upload
Not supporting a drag-and-drop for file upload is kinda quondam fashion, isn't it? Allow us see how to achieve that with a few simple steps.
Kickoff, create a driblet zone and optionally a section to show the uploaded file content. We will employ an image equally a file to drag and drop here.
<div id="container"> <h1>Elevate & Drib an Image</h1> <div id="drop-zone"> Drib HERE </div> <div id="content"> Your image to appear hither.. </div> </div> Get the dropzone and the content areas past their respective ids.
const dropZone = document.getElementById('drop-zone'); const content = document.getElementById('content'); Add together a dragover event handler to bear witness the effect of something going to exist copied,
dropZone.addEventListener('dragover', issue => { event.stopPropagation(); event.preventDefault(); issue.dataTransfer.dropEffect = 'copy'; });
Next, ascertain what we want to exercise when the prototype is dropped. We will demand a drop consequence listener to handle that.
dropZone.addEventListener('drop', outcome => { // Get the files const files = effect.dataTransfer.files; // At present we tin do everything possible to show the // file content in an HTML chemical element similar, DIV }); Endeavor to drag and drop an image file in the CodePen example below and see how it works. Do not forget to run into the code to render the dropped image too.
ten. Handle files with objectURLs
There is a special method called, URL.createObjectURL() to create an unique URL from the file. You can also release it by using URL.revokeObjectURL() method.
The DOM
URL.createObjectURL()andURL.revokeObjectURL()methods let y'all create uncomplicated URL strings that tin be used to reference any information that can be referred to using a DOM File object, including local files on the user'south computer.
A simple usage of the object URL is,
img.src = URL.createObjectURL(file); Use this CodePen to explore the object URL farther. Hint: Compare this arroyo with the approach mentioned in #5 previously.
Determination
I truly believe this,
Many times a native HTML feature may be plenty for united states of america to bargain with the use-cases in hands. I found, file upload is one such that provides many cool options by default.
Let me know if this article was useful to you by commenting beneath. You may also like,
- 10 useful HTML5 features, you may not exist using
- I fabricated a photograph gallery with CSS animation. Here'due south what I learned.
- 10 lesser-known Web APIs y'all may desire to use
If it was useful to yous, delight Like/Share so that, it reaches others as well. Please hit the Subscribe button at the top of the folio to get an email notification on my latest posts.
You can @ me on Twitter (@tapasadhikary) with comments, or feel gratuitous to follow me.
Source: https://blog.greenroots.info/10-useful-html-file-upload-tips-for-web-developers
0 Response to "Html Choose File and Upload Html Choose Folder and Upload"
Post a Comment