Manipulating JSON files in Angular: upload, download, rename, and

Recently, I've been working on enhancing my Angular project by incorporating new functionalities such as file upload, download, renaming, or deletion for JSON files. As someone who is still new to typescript and angular, I could really benefit from some expert advice on the most convenient way to achieve this. Could you please point me in the right direction?

Thank you.

Answer №1

If you're looking to download a file, follow these three steps:

1- Send the appropriate request from the Angular side

download(): Observable<HttpResponse<Blob>> {
return this.http.get<HttpResponse<Blob>>(someURL, {
  observe: 'response',
  responseType: 'blob'
}); as any }

2- In your backend, make sure to set the necessary headers in the response. The following code snippet is for .NET Framework 4.7 and will return CSV file contents:

var contents = new byte[0]; // Insert your file contents here
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new 
ByteArrayContent(contents)};
response.Content.Headers.ContentDisposition = new 
ContentDispositionHeaderValue("attachment")
{
   FileName = file.Name
}
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content- 
Disposition");
response.Content.Headers.ContentType = new MediaTypeHeaderValue ("text/csv");
return response;

3- Finally, subscribe to the http request on the Angular side:

const result 
 = this.service.download()
  .subscribe(res=> {
     let contentDisposition = res.headers.get('content-disposition');
     let filename = contentDisposition.split(';')[1].split('filename') 
         [1].split('=')[1].trim();
     let blob = res.body;
     const url = window.URL.createObjectURL(blob);
     const link = document.createElement('a');
     link.href = url;
     link.download = fileName;
     document.body.appendChild(link);
     link.click();
     window.URL.revokeObjectURL(url);
     link.parentNode.removeChild(link);
   });

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

The Angular overlay panel remains open consistently

I recently developed an Angular component similar to p-overlaypanel, but I'm facing an issue where it remains open for every item I click. What I actually want is for only one overlay panel to be clicked and shown at a time - if I click on another ove ...

Checking the status of a checkbox in Ionic 2

Is there a way to check if an ion-checkbox is marked as checked in Ionic 2? <ion-item *ngFor="let a of q.Answers"> <ion-label>{{a.AnswerDescription}}</ion-label> <ion-checkbox (click)="addValue($event)"></ion-chec ...

Where should the API call be placed in the app.component to halt the system until the response is received and injected into the body, instead of using ngOnInit?

I am currently exploring Angular and experimenting with various features. Recently, I encountered an issue that requires me to take certain actions based on the results returned by a service before the application fully loads. Currently, I am making a cal ...

The React Next app is experiencing issues that are possibly related to updates within a hook

After spending the last hour frustrated and confused, I can't seem to figure out why my code is only displaying the loading spinner but never updates to show the actual data. Even though I can see the data printed in the console, indicating that the d ...

Ways to access or modify variables from a different component in Angular 4 without relying on a service class

Is there a way to interact with or modify variables in another component without using a shared service? I'm dealing with two separate components in my Angular project. Keep in mind that these components are not related as Parent and Child. Compone ...

JSON object representing a nested class

I am facing an issue while attempting to create a JSON object using JavaScript/jQuery. Specifically, I am trying to get the JSON object for Class A and encountering problems with the value of b1 being undefined. Class A { string test1; B b1; } Class B { ...

Creating a React prop type validation that is dependent on the value of another prop

I am in the process of creating a custom React Table component, with the following TableProps structure: export interface ColumnType<ItemType, Key extends keyof ItemType = keyof ItemType> { header: string; key?: keyof ItemType; renderCell: (val ...

"Obtaining the document object within an Angular component: A step-by

Is there a way to access the document object in Angular? I've attempted using ElementRef but it doesn't seem to be working. let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor'); Does anyone have any suggestions ...

Implementing React custom component with conditional typing

My goal is to enable other developers to set a click handler for a button only if the button's type is set to button. Users can only set the type to either button or submit. I want to restrict developers from setting the onClick property on the comp ...

Leveraging ngOnChanges to determine the display of an overlay based on input alterations

Working with TS/Angular on a web application, I made the decision to refactor some code that handles displaying different overlays. Instead of having separate code for each overlay, I consolidated them into one "master overlay" and created a function withi ...

Zero values disappeared from the parameters in an Ajax request

When I send parameters for a WebMethod using Ajax, I receive an object. However, the parameters are losing zeros in the WebMethod. For example, if I send "00001234", on the backend the parameter is received as "1234". Here is the Ajax code that I am using ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

What is the best way to utilize resolve and promises in Angular2 to ensure that data is loaded from the server before rendering a page in the

I am currently developing an Angular 6 application with the requirement to load dynamic routes from a database. To achieve this, I have created a service class called DynamicRoutingService which is responsible for loading both static and dynamic routes fro ...

Incorporate Moment library for date selection in AngularDateRangePicker

I have attempted to implement AngularDateRangePicker according to the instructions provided at the following URL: https://www.npmjs.com/package/ngx-daterangepicker-material However, when I include the line selected: {startDate: Moment, endDate: Moment}; ...

What is the process for creating a join in a REST API that is similar to SQL?

As a beginner in programming, particularly in front-end development, I am curious about how to perform a join in a JSON Restful API. Currently, I am utilizing Json placeholder for my simulated rest API. Despite my attempts to read their documentation, I h ...

Dealing with errors in a Vue application when making requests to an Express

I'm encountering an issue when trying to retrieve the JSON object that comes back with a 400 error. When my Vue app receives this error, it only shows the 400 error code without actual JSON data. Error: Request failed with status code 400 at cre ...

Discover the steps to update the rows, adjust the number of results, and manage pagination in angular-datatable with an observable as the primary data source

Incorporating angular-datatables into my Angular 7 application has been a challenge, especially when it comes to displaying search results efficiently. Within the request-creation-component, a search form is generated. Upon clicking the submit button, an ...

Issues with POST requests in Angular causing failures

I am currently developing a web application using Angular version 5 or higher. My goal is to set up a POST request where the user can input a company name, which will then be saved to a MongoDB database. Given that this is my first Angular project, I am c ...

What is the best way to bundle my Language Server along with my client?

Currently, I am in the process of developing a language server for VSCode which consists of both a client and a server that communicate over RPC. Fortunately, the official documentation includes a fully functional example, where the language server is div ...

User's information will only be updated once the page is refreshed

I am encountering an issue with displaying two ul elements based on user login status. When I log in, the first ul is shown immediately, but the second ul is only displayed after a page refresh. Initially, the value in "accountService.currentUser" is null ...