How can I transfer the data from a file to upload it in Angular 9 without manually typing it out?

In my Angular application, I have a functionality where users can upload two files for processing on the server. However, I am looking to add a feature that allows users to simply copy and paste the contents of the files into two textboxes instead of going through the process of browsing and uploading the files. Below is the code snippet I currently have:

app.component.html

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstfile=null;
  second_file = null;
  title = 'first';
  first_content:any
  content_updated:boolean=false;

  constructor(private http:HttpClient){
    this.content_updated=false;

  }

  firstfileupload(event){
    console.log("First file")
    // console.log(event)
    this.firstfile=event.target.files.item(0)
    this.readFileContent(event.currentTarget.files[0]).subscribe(
      content => {
        for(const line of content.split(/[\r\n]+/)) {
          if (line !== '') {          // <-- regex pattern might return an empty line at the EOF
            console.log(line);
          }
        }
      }

    );
    console.log("Control reached here")
    this.content_updated=true;
    if(this.content_updated===true){
      console.log(this.first_content)
    }
  }
  secondfile(event){
    this.second_file=event.target.files[0];
    this.readFileContent(event.currentTarget.files[0]).subscribe(
      content => {
        for(const line of content.split(/[\r\n]+/)) {
          if (line !== '') {          // <-- regex pattern might return an empty line at the EOF
            console.log(line);
          }
        }
      }
    );
    console.log("Second file uploaded")
  }
  onUpload(){
    console.log("Upload button clicked")
    const fd = new FormData();
    fd.append('files',this.firstfile);
    fd.append('files',this.second_file);
    this.http.post('http://localhost:5000',fd).subscribe(res =>{
      console.log(res)
    }

    )
  }
  private readFileContent(file): Observable<any> {
    let result = new Subject<any>();

    const reader = new FileReader();
    reader.onload = (e) => {
      const fileContent = e.target.result;
      result.next(fileContent);
    };
    reader.readAsText(file);

    return result.asObservable();
  }
}

app.component.html

<h1>Upload the files</h1>
<input type="file" (change)="firstfileupload($event)">
<input type="file" (change)="secondfile($event)">
<button type="button" (click)="onUpload()">Upload</button>
</div>

I am seeking guidance on how to allow users to input the file contents by copying and pasting them into text areas, which are then converted into files and sent to the server. Any suggestions or tips would be greatly appreciated. Thank you.

P.S : Please ignore all the extra code, my focus is just how to get the user input , convert to file and send it to server. In the above code I don't have any logic related to my question, I am just taking the file input.

Answer №1

Here's the HTML code snippet for inputting text:

<div> Type your text below </div>
<textarea id="fileData" [(ngModel)]="data"></textarea>
<button (click)="sendData()">Send Data</button>

And here's the corresponding TypeScript code:

public data = '';
public sendData() {
  this.http.post('http://localhost:5000',this.data).subscribe(res =>{
      console.log(res)
  });
}

If you need to send the data as a file in TypeScript:

public data = '';
    public sendData() {
      var blob = new Blob(["This is my first text."], {type: "text/plain;charset=utf-8"});
      var formData = new FormData();
      formData.append('file',blob);
      this.http.post('http://localhost:5000',formData).subscribe(res => {
          console.log(res)
      });
    }

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

What is the best way to send an object to its matching element?

Imagine having 4 labels and 4 buttons aligned next to each other. While it's common to update the label values by their corresponding button IDs, is there an alternative method using objects or references? <button onclick="myFunction()">Set dem ...

My child template in Angular UI is not loading properly due to the presence of multiple views when the URL changes

After reviewing a couple of questions similar to this on various forums, I may have overlooked a crucial detail in them. Upon loading http://localhost:8000/characters/#/mages/detail/3, I am being redirected to my 'otherwise' URL: $urlRouterProvi ...

Display the uploaded images from uploadify on the webpage

I am currently working on a PHP website that utilizes uploadify for users to upload portfolio images. While I have successfully implemented uploadify, I am now exploring the most effective way to display these uploaded images on the webpage without requir ...

jQuery still not running despite using .ready

I have been attempting to run some jQuery code on my HTML page. After doing some research, I learned that using .ready may be necessary to ensure the DOM is fully loaded before executing the script. Despite this, I am still having trouble getting the scrip ...

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

A hyperlink unveils a visual and conceals its own presence

I'm a beginner in the world of coding and I have a question about creating a link that reveals a hidden image while hiding itself using HTML. After some research, this is what I've come up with: <a href="javascript: ...

When interacting with the iframe in an Ionic3 app, it suddenly crashes

Greetings! I have integrated a flipping book URL inside an iframe: <ng-container> <iframe [src]="eUrl" id="flipping_book_iframe" frameborder="0" allowfullscreen="allowfullsc ...

Clickable link that directs to a particular tab on a webpage (cbpFWTabs)

I have been utilizing tabs from the codrops Tab Styles Inspiration and I am looking for a way to open specific tabs using URLs. For instance, if I wanted to open tab3, I could link it as www.google.com/index#tab3. Below is the code I am currently using: ...

Preventing loss of context in jQuery ajax when mixing HTML/JS and opening a <script> tag

I've encountered a situation where I'm using ajax to communicate with the backend, which is responding with a mix of HTML and JavaScript code. To load this content into a div, I'm using the html() function like so: $("#mydiv").html(ajaxRespo ...

Utilize the unique key generated by Firebase for assigning values to ng-select elements

Version of Angular: 8.2.12 My goal: I am looking to create a form where users can add a new product and choose packaging products for it from another collection. These packaging products may have changing attributes like price, so I aim to link them using ...

Trigger an immediate Primefaces update using a JavaScript function

Having an issue where: upon page load, I attach a 'keypress' event listener to every input field on the page. The goal is to check for special characters in the input and remove them. Below is the function that executes on page load: function ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Error encountered while utilizing the infinite-react-carousel package in React

After entering "npm i infinite-react-carousel --save" into the terminal, an error message appears: "npm ERR! code ERESOLVE "npm ERR! ERESOLVE unable to resolve dependency tree" What could be causing this issue? How can I troubleshoot and resolve it? I h ...

Looking to display an alert message upon scrolling down a specific division element in HTML

In the midst of the body tag, I have a div element. <div id="place"> </div> I'm trying to achieve a scenario where upon scrolling down and encountering the div with the ID "place", an alert is displayed. My current approach involves che ...

Is there a convenient method for setting up and activating real-time TypeScript checking in Windows 10 using VS Code?

After successfully installing VS Code on my Windows 10 system, I decided to follow the instructions provided here. Upon completion, Node and NPM were also installed correctly. However, I noticed a gap in the setup instructions between installing TypeScrip ...

Tips on setting the first root element to automatically expand in a tree component

Currently, I am utilizing a tree component that includes partially loaded data. For reference, here is the link to the stackblitz example: StackBlitz. Is there a way for me to have the child element of the first root element automatically opened by defau ...

Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user se ...

Confirmation message for deletion using jQuery on dynamic elements

My div is populated with dynamically added records. Whenever I click on the 'Remove' link, a confirmation box pops up multiple times corresponding to the number of records present in the div. I want the confirmation box to appear only for the spe ...

Using Node's Express bodyParser() to access a JSON string that has been parsed

Question: How can I retrieve the parsed JSON object from the server side? I have successfully sent a JSON string to the server, but I am having trouble accessing the object once it is parsed. The client-side script for sending the JSON data is as follows ...