Tips for resetting and enabling file uploads with ng2-file-upload

My file upload functionality is working smoothly using ng2-file-upload. However, I am facing a challenge in handling server-side errors and resetting the file uploader. How can I achieve this? Below are the snippets of code that I am currently using:

HTML

<div class="progress progressbar" style="height:10px;">
<div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
</div>
<button type="button" class="btn btn-warning btn-s button_gray" (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-s button_gray" (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
<button type="button" class="btn btn-primary btn-s" (click)="uploader.authToken=authToken ;uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>

Typescript

ngOnInit() {
this.uploader.onAfterAddingFile = (file) => {
file.withCredentials = false;
if (this.target) this.target.value = '';
};
this.uploader.onErrorItem = (item, response, status, headers) => this.onErrorItem(item, response, status, headers);
this.uploader.onSuccessItem = (item, response, status, headers) => this.onSuccessItem(item, response, status, headers);
}

let data = JSON.parse(response); //success server response
console.log(data)
this.showSnackBar('Successfully Uploaded file.');
this.router.navigate(['/result'])
}

onErrorItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any {
let error;
if (response != undefined && response.length > 0)
JSON.parse(response); //error server response
else
error = response;

console.log(error)
this.showSnackBar('Error on Upload the file.');
}

If there is a failure, I am encountering difficulty re-uploading the file.

Answer №1

I believe the issue has been resolved, but I still want to share the complete solution with the community

1- First, include the following in the component

import { ViewChild, ElementRef } from "@angular/core";

2- Next, add this declaration to the component

@ViewChild("dummyID", { static: false }) 
myInputVariable: ElementRef; 

3- In the HTML file, assign an ID to the specific element (I used #dummyID)

<input #dummyID type="file" ng2FileSelect [uploader]="uploader" />

4- Now, you can access the element within the component. It is recommended to use it in the onWhenAddingFileFailed method of ng2-file-upload for best practices

this.uploader.onWhenAddingFileFailed = item => {
//some code
//some code

 this.myInputVariable.nativeElement.value = "";
};

Answer №2

To clear the queue, simply reset it.

this.queueManager.clearQueue();

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

Is it possible for me to create a union type that connects parameters and responses in a cohesive manner

I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type. For instance, consider the following scenario: type ResponseMap = { requestPath: ...

Making Angular2 Templates More Efficient with Array.prototype.filter()

I have a variable named networkInterface that includes an array called services. My objective is to create a checkbox input that indicates whether a specific service_id exists within the services array of the networkInterface. An illustration of JSON `int ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Creating pagination functionality for a React Material table

Check out this Spring Boot endpoint that I use for retrieving items from the database: import React, { useEffect, useState } from "react"; // Additional imports export default function BusinessCustomersTable() { // Functionality and code impl ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Outputting a JS file per component using Rollup and Typescript

Currently, I am in the process of developing a component library using React, TypeScript, and Rollup. Although bundling all components into a single output file index.js is functioning smoothly, I am facing an issue where individual components do not have ...

The error occurs when trying to access the `pipe` property of an undefined variable in NgbTypeahead

I am currently working on implementing the typeahead directive of ng-bootstrap. Below is the code snippet from my HTML file: <input type="text" class="form-control" formControlName="payee" autofocus [ngbTypeahead]="searchPayee"> Here's the cor ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

Attempting to bind an input parameter using NgStyle in Angular version 2 and above

Issue: I am in need of a single component (spacer) with a width of 100% and a customizable height that can be specified wherever it is used in the HTML (specifically in home.html for testing): number 1 <spacer height="'200px'"></spa ...

Using conditional statements to localize in Angular

In my Angular application, I am utilizing i18n for internationalization purposes. When it comes to HTML, I use i18n="@@<unique_Id>" and for dynamic elements defined in TypeScript class files, I use $localize. For example: this.buttontext = ...

The 'undefined' type cannot be assigned to the 'never' type

interface A { name?: string age: number } var a: A = { name: '', age: 23 } var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => { if (a[key] || a[key] === 0) { prev[key] = a[key] // an error was reporte ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Having trouble with Strapi API requests? Getting the error message: "Module failed to self-register"?

I'm encountering an issue when attempting to use the Strapi API, as I keep receiving the following error message: /Users/xxxxxxxxxxxxx/node_modules/snappy/build/Release/binding.node'. at Object.Module._extensions..node (internal/modules/cjs/l ...

Angular2 encountered a TypeError stating that self._el_11 is not a valid function

Looking to attach an event listener to an input field? Check out the code snippet below: <input ref-search (keyup)="search(search.value)"> Here is the corresponding search method: search(condition: string){ console.log(condition); } When ente ...

Tips on utilizing a pre-defined parametrized selector within the createSelector function

My goal is to create a selector based on a parametrized selector. I believe this approach will only emit when a specific item is updated, which aligns with my requirements. const getFeatureState = createFeatureSelector<FragmentsHierarchyState>(MY_FE ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Tips for properly utilizing GeolocationPosition in TypeScript

Our goal is to utilize the Geolocation API to access the user's location. This particular code snippet appears to be functioning well: if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position: GeolocationPosition) => conso ...

Guide to setting up a one-to-many self relation entry in Prisma

I am facing a challenge with a simple schema model that includes one-to-many self relations. In this scenario, my goal is to create a parent entity along with its children in a single transaction. How can I accomplish this task effectively? data-model Y{ ...

Is it necessary to include the <script> tag in the HTML file when importing React through npm in vscode?

Just starting out with React in vscode and feeling a bit lost. If I install React using npm in vscode and include import React from "react"; at the top of my .js file, will that be enough to use React? Or do I still need to include a <script& ...