DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Implement File Upload in Angular
  • Upload and Retrieve Files/Images Using Spring Boot, Angular, and MySQL
  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions

Trending

  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Handle Folder Uploads in Angular 2+

How to Handle Folder Uploads in Angular 2+

In this post, we examine how you can create a file upload functionality within your Angular-based web application. Read on for more!

By 
Ben Jacobson user avatar
Ben Jacobson
·
Updated Jan. 22, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
23.7K Views

Join the DZone community and get the full member experience.

Join For Free

At Lucidpress, we recently decided to revamp our image manager experience by creating a completely new image manager written in Angular 2 and TypeScript. One of the key new features we wanted to add was bulk image upload, which is the ability to upload a folder with all of its contents while maintaining the original folder structure. There are two ways for a user to initiate folder uploads:

  • Drag and drop a folder.
  • Provide a file picker that allows folder selection.

It took a little research to find the modern method for handling folder uploads. I compiled a few code snippets with explanations as a quick reference for others. Here’s a look at how you can implement this feature in your web app.

Drag and Drop

With HTML5 came a well-established Drag and Drop API. When you drop a folder, a drop event is received with a file item as part of the data transfer. The only way to access the contents of this folder is through the webkit filesystem API, which is not part of HTML5. A DataTransfer file has a webkitGetAsEntry method which returns the webkitEntry for the file (supported only in Chrome, Firefox, and Edge). Each webkit entry can either be a file or a directory—use isFile and isDirectory to determine which kind.

function drop(event) {
    const items = event.dataTransfer.items;
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (item.kind === 'file') {
            const entry = item.webkitGetAsEntry();
            if (entry.isFile) {
                ...
            } else if (entry.isDirectory) {
                ...
            }
        }
    }
}

If the entry is a file entry, the file blob can be accessed with the file method.

function parseFileEntry(fileEntry) {
    return new Promise((resolve, reject) => {
        fileEntry.file(
            file => {
                resolve(file);
            },
            err => {
                reject(err);
            }
        );
    });
}

If the entry is a directory entry, all of the sub-entries in the directory can be accessed with the readEntries method on a directory reader. Create a directory reader for a directory entry by calling the createReader method on the directory entry.

function parseDirectoryEntry(directoryEntry) {
    const directoryReader = directoryEntry.createReader();
    return new Promise((resolve, reject) => {
        directoryReader.readEntries(
            entries => {
                resolve(entries);
            },
            err => {
                reject(err);
            }
        );
    });
}

The only help Angular offers is the ability to easily bind component methods to the drag and drop events. If your component has the public methods dragenter, dragover, and drop, you can bind them like this:

<div
  id="drop-area"
  (dragenter)="dragenter($event)"
  (dragover)="dragover($event)"
  (drop)="drop($event)"
>
</div>

Folder Picker

The standard way to upload a file is to have the user click on an input HTML element of type file. This allows users to select multiple files when the multiple attribute is given. HTML5 itself does not support a directory mode for the file picker, but webkit can give us this functionality. Add the webkitdirectory attribute to an input of type file, and it will only allow the selection of folders. Once the user selects their folder, the change event is fired, and the payload is contained in the files property.

<input
    #folderInput
    type="file"
    (change)="filesPicked(folderInput.files)"
    webkitDirectory
>

No directory tree parsing is necessary here because the payload returned is a FileList object containing each of the files that existed at any depth in the selected directory. The webkitRelativePath property of each file contains a string representing the relative path to the directory selected. This string can be parsed to recreate the tree structure from the user’s file system.

function filesPicked(files) {
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const path = file.webkitRelativePath.split('/');
    // upload file using path
        ...
    }
}

The only help Angular offers in this scenario is the ability to easily name the input element for quick reference to avoid a call to document.getElementById.

As you can see, folder upload can be achieved without Angular, though it integrates easily into an existing Angular app. These webkit folder features are currently only supported in Chrome, Firefox, and Edge.

Upload AngularJS Directory

Published at DZone with permission of Ben Jacobson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Implement File Upload in Angular
  • Upload and Retrieve Files/Images Using Spring Boot, Angular, and MySQL
  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!