1

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);
    }
}
jojo
  • 13,583
  • 35
  • 90
  • 123

1 Answers1

1

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

Zilong Wang
  • 564
  • 4
  • 14
  • I tried your example and got "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.com/rest/upload/avatar. This can be fixed by moving the resource to the same domain or enabling CORS.". I tries with enabling CORS on my api but I still get this error – Dimuthu Feb 06 '16 at 09:20
  • In my project, I add a filter to add Http header
    HttpServletResponse res = (HttpServletResponse) response;
    res.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
    res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    res.addHeader("Access-Control-Allow-Headers", "Content-Type");
    res.addHeader("Access-Control-Allow-Credentials", "true");
    – Zilong Wang Feb 18 '16 at 14:52