【问题标题】:how to post a form with payload in angular 2?如何以角度 2 发布带有有效负载的表单?
【发布时间】:2016-04-23 08:15:57
【问题描述】:

我正在玩 angular 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);
    }
}

【问题讨论】:

  • 您需要专门的表格,还是只想上传文件?
  • 看看这个问题,希望对你有帮助:stackoverflow.com/questions/36352405/…
  • 这里似乎缺少 $event 参数 (ngSubmit)="onSubmit($event)"

标签: angular angular2-forms


【解决方案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

【讨论】:

  • 我尝试了您的示例并得到“跨域请求被阻止:同源策略不允许读取example.com/rest/upload/avatar 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决."。我尝试在我的 api 上启用 CORS,但我仍然收到此错误
  • 在我的项目中,我添加了一个过滤器来添加Http header
    HttpServletResponse res = (HttpServletResponse) response;
    res.addHeader("Access-Control-Allow-Origin", "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") ;
猜你喜欢
  • 1970-01-01
  • 2014-12-21
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
相关资源
最近更新 更多