jojo
jojo

Reputation: 13843

how to post a form with payload in angular 2?

I am playing with angular 2, try to create a sample app that upload a file. Have below view and component, when i click submit, i don`t see any request is coming out from browser.

if i add (ngSubmit)="onSubmit()" to form, i can see onSubmit is invoked, but i don`t see anything pass into it.

Question: what is the right way to get proper binding so that i can have a valid file upload form?

Template:

<form action="api/upload" method="POST" enctype="multipart/form-data" class="btn-group" role="group">
    <input type="file" class="btn btn-lg btn-default" required>
    <input type="submit" value="Upload" class="btn btn-lg btn-primary upload-btn">
</form>

Component:

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES}    from 'angular2/common';

@Component({
    selector: 'my-app',
    directives: [FORM_DIRECTIVES],
    template: 'path-to-template'
})

export class AppComponent {
    onSubmit(e) {
        // TODO: get payload from form and upload to server
        console.log(e);
    }
}

Upvotes: 1

Views: 4457

Answers (1)

Zilong Wang
Zilong Wang

Reputation: 584

In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.

html code

<input type="file" (change)="selectFile($event)">

ts code

selectFile($event): void {
  var inputValue = $event.target;
  this.file = inputValue.files[0];
  console.debug("Input File name: " + this.file.name + " type:" + this.file.size + " size:" + this.file.size);
}

upload code:

const URL = 'http://www.example.com/rest/upload/avatar'; 

uploader:MultipartUploader = new MultipartUploader({url: URL});

item:MultipartItem = new MultipartItem(this.uploader);

if (this.item == null){
   this.item = new MultipartItem(this.uploader);
}
if (this.item.formData == null)
  this.item.formData = new FormData();

this.item.formData.append("file",  this.file);

this.item.callback = this.uploadCallback;
this.item.upload();

Here is example : https://github.com/wangzilong/angular2-multipartForm

Upvotes: 1

Related Questions