How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met:

1. Only allow uploading of zip files; display an error message for other file types 
2. Restrict the file size to be under 3 MBs; show an error message if it exceeds this limit
3. Upon selecting a zip file, display a progress bar but only initiate file upload via REST API call after clicking a separate 'Register' button.

Here is what I have implemented so far:File Upload Service

postFile(fileToUpload: File, header): Observable<any> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    if (fileToUpload.size <= 3048576)
    return this.httpClient.post(endpoint, formData, { headers: header })
      .pipe(map(data => {
        console.log(data);
        return data;
      },error => {
        console.log(error, 'reduce file size');
      })) 
    }

Component TS File

handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
  this.fileUploadService.postFile(this.fileToUpload, this.headers).subscribe(data => {
    // do something, if upload success
    console.log('the file has been uploaded successfully', data);
    }, error => {
      console.log(error);
    });
}

Component HTML

<input type="file"
 id="file" (change)="handleFileInput($event.target.files)">

I would appreciate any suggestions on how to enhance my implementation to meet these specifications.

Answer №1

When working with file uploads, it's important to include a validation function in your code for both the file extension and size. This ensures that only valid files are uploaded. Providing feedback to the user when validation fails is also recommended.

To track file upload progress and show a progress bar, you can enhance the .post method by adding extra options and listening for specific events:

return this.httpClient.post(endpoint, formData, { 
 headers: header,
 reportProgress: true, 
 observe: 'events'
}).pipe(map(event => {  
 if (event.type === HttpEventType.Response) {
  // Upload complete
 }
 if (event.type === HttpEventType.UploadProgress) {    
  // Use event.loaded and event.total to display the progress bar
 }
})) 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Floating CSS containers

Apologies for not including a picture. You can view the design I am trying to achieve here. I am attempting to create two boxes with a third box below them, and another box on the right side of the layout. All enclosed within a larger container. Everythin ...

What is the technique for filtering multiple values using the OR operation in ng-model functions?

Currently, I am using an ng-modal labeled as "myQuery." At the moment, there are two filters in place that look like this: <accordion-group heading="" ng-repeat="hungry_pets in Pets" | filter:{hungry:false} | filter:{name:myQuery}" ... > I have ...

Setting both the height and row height of the table is not allowed

Currently employing js DataTable, I aim to establish a default height for the table and row. My current approach is as follows: $(document).ready(function() { var table = $('#example').DataTable ({ iDisplayLength: 15, "bLen ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

What is the best way to select an element based on its relationship to another Element object using a selector?

I am currently developing a small library in which I require the ability to select a relative element to the targeted element using the querySelector method. For instance: HTML <div class="target"></div> <div class="relative"></div& ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

The onbeforeunload event should not be triggered when the page is refreshed using a clicked button

Incorporated into my webpage is a sign-up form. I would like it to function in a way that if the user accidentally refreshes, closes the tab, or shuts down the browser after entering information, a specific message will appear. <input type="text" place ...

Implementing automatic dark mode activation during nighttime with jQuery or JavaScript

I'm looking to implement an automatic dark mode feature on my website that switches on at night and off during the day or morning. Currently, my website has a dark mode toggle code that allows users to switch between dark and light modes using local ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Tips for deleting extraneous cells in a table without altering the placement of the other cells and refraining from employing CSS

I'm struggling with understanding how to merge cells in a table. Can someone explain the rules for merging table cells to me? I want to remove certain cells from the table without using CSS, I just want to make it look clean. <table border="1" ...

Sidebar Masonry - Use Bootstrap for a Unique Layout

My goal is to have the page divided into 4 rows, with Masonry aligning the posts within 3 rows and a sidebar displayed on the right. However, I am facing an issue where Masonry mixes everything up and does not allow me to have a sidebar at the right. HTML ...

JavaScript multi-click navigation menu

I'm relatively new to JavaScript and I've been struggling with using multiple onClick attributes. While I have some code that works, I feel like there might be a simpler and cleaner solution to my problem. What I'm trying to achieve is a na ...

Difficulty arises in designing a tableless layout due to the issue of auto

Wondering why my page is not expanding with its content? Check out my demo on Fiddle http://jsfiddle.net/msas3/. The light blue area should determine the overall height of the page. ...

Angular - Error: Unable to assign value to a reference or variable

I am currently working on an app built with Angular 8. app.component.html <div> <label class="form-check-label f-14"> <input type="checkbox" class="form-check-input" name="isAgree" [(ngModel)]="isAgree" #isAgree="ngModel"/> ...

Make sure to blur all images whenever one of them is clicked

I am currently facing an issue with my webpage where I have 3 images displayed. I have implemented an event listener to detect clicks on the images, and once a click occurs on one of them, I want everything else on the page to become blurred, including the ...

Smooth transitions between points in animations using the D3 easing function

I'm working on an animated line chart that displays data related to play activities. I've been experimenting with changing the animation style between data points on the chart using d3.ease Currently, my code looks like this: path .attr("stro ...

angular change digits to Persian script

I am trying to convert English numbers to Persian numbers in angular 4: persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]; engli ...

Understanding the integration of sass with webpack in an Angular 4 project

Is it possible to reference a sass file instead of a css file directly in the index.html? If so, how does webpack compile the sass into a css file? Additionally, what is the most effective way to bundle the sass file when building the application? The ve ...

Tips for creating responsive designs with specific media queries for various device sizes

I am looking to create a responsive website using media queries and have already created different media queries for mobile, tablets, and desktops. However, I am unsure if I should be writing the same CSS code multiple times for various device sizes, such ...