2016-01-18 41 views
1

我正在玩angular 2,嘗試創建上傳文件的示例應用程序。 有下面的視圖和組件,當我點擊提交時,我看不到任何請求從瀏覽器出來。如何發佈角度爲2的有效載荷的表格

如果我添加(ngSubmit)=「onSubmit()」形式,我可以看到onSubmit被調用,但我沒有看到任何東西傳入它。

問:什麼是正確的方式來獲得正確的綁定,以便我可以有一個有效的文件上傳形式?

模板:

<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> 

組件:

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); 
    } 
} 
+1

你需要明確形成,或者你只是想上傳f ILE? – eesdil

+0

看看這個問題,希望它有幫助:http://stackoverflow.com/questions/36352405/file-upload-with-angular2-to-rest-api – amay0048

回答

-4

有一個在angular2兩種不同的形式。 1.模型驅動形式 2.模板驅動形式

使用它們中的任何一個。參考這link它們實現了模型驅動的形式。

+0

我認爲他問如何發佈多部分表單數據,而不是使用哪種形式 – amay0048

1

在我的項目中,我使用XMLHttpRequest發送multipart/form-data。 我認爲它會適合你。

HTML代碼

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

TS碼

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); 
} 

上傳代碼:

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(); 

這裏是例子:https://github.com/wangzilong/angular2-multipartForm

+0

我試過你的例子,並得到了「跨源請求被阻止:同源策略不允許讀取http://www.example.com/rest/upload/avatar上的遠程資源,這可以修復通過將資源移動到相同的域或啓用CORS。「。我試着在我的api上啓用CORS,但我仍然得到這個錯誤 – Dimuthu

+0

在我的項目中,我添加了一個過濾器來添加Http標頭
HttpServletResponse res =(HttpServletResponse)響應;
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」); –

相關問題