<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Mukesh Soni</title>
    <description>The latest articles on Forem by Mukesh Soni (@mukesshsoni).</description>
    <link>https://forem.com/mukesshsoni</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1016567%2F95ed212b-5e31-443c-8ace-cd9d641b5531.jpg</url>
      <title>Forem: Mukesh Soni</title>
      <link>https://forem.com/mukesshsoni</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/mukesshsoni"/>
    <language>en</language>
    <item>
      <title>How to Save and Download Text in an HTML File in Angular 16 Using HttpClient</title>
      <dc:creator>Mukesh Soni</dc:creator>
      <pubDate>Fri, 12 Jul 2024 13:27:35 +0000</pubDate>
      <link>https://forem.com/mukesshsoni/how-to-save-and-download-text-in-an-html-file-in-angular-16-using-httpclient-3d4i</link>
      <guid>https://forem.com/mukesshsoni/how-to-save-and-download-text-in-an-html-file-in-angular-16-using-httpclient-3d4i</guid>
      <description>&lt;p&gt;In modern web applications, there are scenarios where you need to save text content in an HTML file, read the file, and send its content to a server as form-data. This guide will walk you through achieving this in an Angular 16 application using Angular's HttpClient.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before we dive in, ensure you have the following installed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node.js and npm&lt;/li&gt;
&lt;li&gt;Angular CLI&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you haven't installed Angular CLI, you can do so using npm:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @angular/cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Setting Up the Angular Application
&lt;/h2&gt;

&lt;p&gt;Create a new Angular application if you don't have one already:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng new angular-file-upload
cd angular-file-upload
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add &lt;code&gt;HttpClientModule&lt;/code&gt; to your Angular project. Open &lt;code&gt;app.module.ts&lt;/code&gt; and add it to the imports array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { FileService } from './file.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [FileService],
  bootstrap: [AppComponent]
})
export class AppModule { }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating the FileService
&lt;/h2&gt;

&lt;p&gt;First, we need a service to handle file operations. Create a new service:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng generate service file
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;file.service.ts&lt;/code&gt;, add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class FileService {
  private tempFileUrl: string | null = null;

  saveHtmlFile(content: string): string {
    const blob = new Blob([content], { type: 'text/html' });
    this.tempFileUrl = window.URL.createObjectURL(blob);
    return this.tempFileUrl;
  }

  getTempFileUrl(): string | null {
    return this.tempFileUrl;
  }

  revokeTempFileUrl(): void {
    if (this.tempFileUrl) {
      window.URL.revokeObjectURL(this.tempFileUrl);
      this.tempFileUrl = null;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Component Implementation
&lt;/h2&gt;

&lt;p&gt;Now, let's implement the component to save text content in an HTML file, read it, and send it as form-data using &lt;code&gt;HttpClient&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Update your component (&lt;code&gt;app.component.ts&lt;/code&gt;) with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FileService } from './file.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private fileService: FileService, private http: HttpClient) { }

  saveHtmlContent() {
    const content = `
      &amp;lt;html&amp;gt;
        &amp;lt;head&amp;gt;
          &amp;lt;title&amp;gt;Sample HTML File&amp;lt;/title&amp;gt;
        &amp;lt;/head&amp;gt;
        &amp;lt;body&amp;gt;
          &amp;lt;h1&amp;gt;Hello, World!&amp;lt;/h1&amp;gt;
          &amp;lt;p&amp;gt;This is a sample HTML file.&amp;lt;/p&amp;gt;
        &amp;lt;/body&amp;gt;
      &amp;lt;/html&amp;gt;
    `;

    const fileUrl = this.fileService.saveHtmlFile(content);
    console.log('Temporary HTML File URL:', fileUrl);
  }

  async sendFileAsFormData() {
    const fileUrl = this.fileService.getTempFileUrl();
    if (!fileUrl) {
      console.error('No temporary file URL available');
      return;
    }

    try {
      const response = await fetch(fileUrl);
      const content = await response.text();

      // Create a Blob from the content
      const blob = new Blob([content], { type: 'text/html' });
      const formData = new FormData();
      formData.append('file', blob, 'sample.html'); // 'sample.html' is the file name

      // Send the form-data using HttpClient with response type 'blob'
      this.http.post('https://your-api-endpoint.com/upload', formData, { responseType: 'blob' })
        .subscribe(blob =&amp;gt; {
          // Handle the blob response
          const downloadUrl = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = downloadUrl;
          link.download = 'response-file.html'; // Name of the downloaded file
          link.click();
          window.URL.revokeObjectURL(downloadUrl);

          console.log('File downloaded successfully');
        }, error =&amp;gt; {
          console.error('Error sending file content:', error);
        });

    } catch (error) {
      console.error('Error reading file content:', error);
    } finally {
      this.fileService.revokeTempFileUrl();
    }
  }

  clearTempFile() {
    this.fileService.revokeTempFileUrl();
    console.log('Temporary file URL revoked');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Template
&lt;/h2&gt;

&lt;p&gt;Update the component template (&lt;code&gt;app.component.html&lt;/code&gt;) to include buttons for saving and uploading the HTML content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
  &amp;lt;button (click)="saveHtmlContent()"&amp;gt;Save Content as HTML&amp;lt;/button&amp;gt;
  &amp;lt;button (click)="sendFileAsFormData()"&amp;gt;Send Saved HTML as Form-Data and Download Blob&amp;lt;/button&amp;gt;
  &amp;lt;button (click)="clearTempFile()"&amp;gt;Clear Temporary File&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Explanation
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;saveHtmlContent()&lt;/code&gt;&lt;/strong&gt;: This method saves text content in an HTML file and logs the temporary URL.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;&lt;code&gt;sendFileAsFormData()&lt;/code&gt;&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt; Fetches the file content using the temporary URL. &lt;/li&gt;
&lt;li&gt; Creates a Blob from the fetched content. &lt;/li&gt;
&lt;li&gt; Creates a &lt;strong&gt;&lt;code&gt;FormData&lt;/code&gt;&lt;/strong&gt; object and appends the Blob to it. &lt;/li&gt;
&lt;li&gt; Sends the &lt;strong&gt;&lt;code&gt;FormData&lt;/code&gt;&lt;/strong&gt; object in an HTTP POST request to the specified API endpoint, configuring Angular's &lt;strong&gt;&lt;code&gt;HttpClient&lt;/code&gt;&lt;/strong&gt; to expect a &lt;strong&gt;&lt;code&gt;blob&lt;/code&gt;&lt;/strong&gt; response. &lt;/li&gt;
&lt;li&gt; Handles the blob response by creating a download link and triggering a download of the received file. &lt;/li&gt;
&lt;li&gt; Logs success or error messages.&lt;/li&gt;
&lt;li&gt; Revokes the temporary file URL after the request is complete.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;&lt;code&gt;clearTempFile()&lt;/code&gt;&lt;/strong&gt;: This method clears the temporary URL to free up memory.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>html</category>
    </item>
  </channel>
</rss>
