Typescript form data file

Post/Upload FormData (multipart/form-data) with Angular 10, TypeScript and HttpClient

Post/Upload FormData (multipart/form-data) with Angular 10, TypeScript and HttpClient

In this post we will give you information about Post/Upload FormData (multipart/form-data) with Angular 10, TypeScript and HttpClient. Hear we will give you detail about Post/Upload FormData (multipart/form-data) with Angular 10, TypeScript and HttpClientAnd how to use it also give you demo for it if it is necessary.

In this quick how-to tutorial, you’ll learn how to work with FormData in Angular 10 and TypeScript and how to post it to a web server via a POST request and HttpClient .

One of the most important aspects of web development is forms as they allow you to collect data from users and upload it to servers.

If you are new to these how-tos, check out how to install and set up a project and the prerequisites.

There are various ways to work with forms in JavaScript and HTML. Also different frameworks (such as Angular) added other ways to handle forms.

In this tutorial, we’ll be looking at FormData , A browser API for handling forms data just like its name suggests. This API provides methods and properties that enable you to have access and work with form elements and their values in a straightforward way.

It’s particularly helpful if you are working with client side frameworks like Angular as it allows you to easily prepare form data to be sent with POST HTTP requests.

Note: You can think of FormData as a representation of an HTML form in JavaScript instead of HTML.

You also can create a FormData instance from an HTML form.

The FormData API allows you to create a set of key/value elements that correspond to form fields and their values. This can be then sent to the server using Angular HttpClient.

Note: A FormData instance is equivalent to an HTML form sent using the multipart/form-data encoding.

How to use FormData in Angular 10?

Let’s now see an example of how you can create a FormData instance and send it with HttpClient POST in Angular 10.

Note: We assume that you have a server running at the http://localhost:3000 address with an /upload that accepts POST requests for uploading files in your server.

If you would like to create a server for uploading files, check out Nest.js Tutorial: File Uploading with Multer and Serving Static Files in Nest.

Provided that you have created an Angular 10 project with Angular CLI, navigate to your project’s root folder and run the following command to generate a component that we’ll be working with:

$ ng generate component upload

Open the src/app/upload/upload.component.html file and add the following form:

 Angular 10 FormData (multipart/data-form) Example [formGroup]="uploadForm"(ngSubmit)="onSubmit()"> type="file"name="profile"(change)="onFileSelect($event)"/>  type="submit">Upload    

You can also check this example with HTML pre.

Next, open the src/app/upload/upload.component.ts file and start by importing these modules:

importFormBuilder,FormGroup>from'@angular/forms';importHttpClient>from'@angular/common/http';

We import FormBuilder and FormGroup from the @angular/forms package which are necessary to create a reactive form in Angular. We also import HttpClient that will be used to send data to the server.

Note: Make sure to import ReactiveFormsModule and HttpClientModule in your main module application which exists in the src/app/app.module.ts file and add them to the imports array.

Using HttpClient calls directly from your components is against the separation of concerns principle but this is just a simple example. Typically, you would need to create a service and make HttpClient from the service.

Next define the SERVER_URL and uploadForm variables in your component:

exportclassUploadComponentimplementsOnInitSERVER_URL="http://localhost:3000/upload";uploadForm:FormGroup;

Next, import and inject HttpClient and FormBuilder :

exportclassUploadComponentimplementsOnInitconstructor(privateformBuilder:FormBuilder,privatehttpClient:HttpClient)>

Next, create a reactive form in ngOnInit() method of the component which gets called when the component is initialized:

ngOnInit()this.uploadForm=this.formBuilder.group(profile:['']>);>

Next, let’s add the onFileSelect() method which gets called when a file is selected by the user:

onFileSelect(event)if(event.target.files.length> )constfile=event.target.files[ ];this.uploadForm.get('profile').setValue(file);>>

We simply check if at least one file is selected and we set the profile field of uploadForm to the selected file.

Finally, let’s see how we can use FormData to send multipart/form-data to our server. Let’s define the onSubmit() method:

onSubmit()constformData=newFormData();formData.append('file',this.uploadForm.get('profile').value);this.httpClient.postany>(this.SERVER_URL,formData).subscribe((res)=>console.log(res),(err)=>console.log(err));>

We simply create an instance of FormData , next we add fields with their values using the append() method of FormData . In our example, we only add a field named file which holds the value the selected file. Finally we use the post() method of HttpClient to send the form data to the server.

For reference, FormData provides the following methods for working with form data:

  • The FormData.append() appends a new value for an existing key, or adds the key if it does not exist.
  • The FormData.delete() method deletes a key/value pair from a FormData object.
  • The FormData.entries() method provides an iterator for going through all key/value pairs of the instance.
  • The FormData.get() method Returns the first value associated with a given key from within a FormData object.
  • The FormData.getAll() method provides an array of all the values associated with a specific key.
  • The FormData.has() methods provides a boolean indicating whether a FormData instance contains a specific key.
  • The FormData.keys() method provides an iterator for going through all the keys contained in the form instance.
  • The FormData.set() method sets a new value for an existing key inside a FormData object, or adds the key/value if it does not exist.
  • The FormData.values() method provides an iterator for going through all values contained in this object.

Conclusion

In this tutorial, we’ve seen how to send post multi-part form data to a server using TypeScript, Angular 10, HttpClient and FormData .

Hope this code and post will helped you for implement Post/Upload FormData (multipart/form-data) with Angular 10, TypeScript and HttpClient. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

Источник

FormData in TypeScript

I’m trying to get in the habit of writing a post about anything that takes me more than, say, 15 minutes of trial and error and Google to get right. Chances are I’m not the first nor the last to hit any particular roadblock. This is both a tutorial and a request for help! edit: @foresthoffman provided the help I needed! I’ve updated the post to include the fix. I’m working on a small toy app that needs a few controls to specify how to draw something to the canvas. A seems like the natural choice for this, but using the data from TypeScript proved a little bit tricky. The MDN page on FormData suggests using syntax like the following:

const form = document.querySelector('form') const data = new FormData(form); for (const pair of data)  // cool stuff > // OR for (const pair of data.entries())  // cool stuff > 

I had no luck with these. Using for..of causes TypeScript to complain that data is not an iterator (I think it is, or at least in JS it can be used like one with for. of ), or that data has no such property entries . This makes a little more sense — it doesn’t yet in all environments. I tried tweaking my tsconfig.json to target esnext but that didn’t do it, and I’d rather keep that set to es5 anyway. Switching to use for..in on data does what you’d expect, really — it enumerates all of the methods available on data :

const data = new FormData(form); for (const entry in data)  console.log(entry); > /* get getAll has set entries keys values forEach */ 

Neat, I guess, but not what I’m looking for! Frustratingly, entries appears. Why can I not use it? It turns out the fix for this is subtle — you need to specifically tell TypeScript you’re going to be using this method by adding dom.iterable to your tsconfig.json — it’s not automatically brought in with «dom»:

"lib": [ "dom", "dom.iterable", "esnext" ], 

Now you can for (let entry of data.entries()) to your heart’s content! That’s still not as concise as it could be, though — in JavaScript you can just write (let entry of data) . We can allow this pattern in TypeScript by adding one more line to tsconfig.json :

This compiler option «provide[s] full support for iterables in ‘for-of’, spread, and destructuring when targeting ‘ES5’ or ‘ES3’.» Now our code can match the JS exactly! I’m leaving my workaround for posterity, because in some simple cases I’d prefer to skip the iterator and do it this way anyway. It simply doesn’t iterate at all, it looks for what it needs. As an example, here’s part of the form in question:

   Choices  type="radio" name="choice" id="choice1" value="choice1" checked>  for="choice1">Choice 1  type="radio" name="choice" id="choice2" value="choice2">  for="choice2">Choice 2   type="submit">Do The Thing!  
const form = document.querySelector('form')!; form.onsubmit = (_) =>  const data = new FormData(form); const choice = data.get('choice') as string; doCoolThing(choice); return false; // prevent reload >; 

A few TypeScript-y things to note — I’m using the ! operator at the end of the querySelector call. This is the non-null assertion operator — querySelector returns a value of type Element | null . I prefer to keep strictNullChecks on, so TS doesn’t enjoy me trying to operate on form as if it were an element — this operator tells the compiler that I promise there will be a form to select and it won’t return null. Also, FormData.get() returns a value of type string | File | null . This is another case where I’ve quite literally just written the form myself — I know it’s gonna be a string. I’m using as to cast to the proper type. Finally, I return false to prevent the page from actually reloading — the re-draw to the canvas happens inside doCoolThing , and if the page reloads it’ll disappear along with the form data! I’m not sending anything to a server, just using the user input locally on the page. This does do the trick — I can just grab the the form data I want one at a time without using the iterator to configure the output.

Источник

Читайте также:  Qt designer pushbutton python
Оцените статью