繁体   English   中英

Angular如何以编程方式发送表单数据

[英]Angular how to progamatically send a Form Data

在线上似乎没有关于发送带有表单数据的api请求的优质文档。

当您使用google时,google会自动假定您要创建客户端反应式表单gui,因此该API的实际部分将被定罪。

即使您按照他们的指南进行操作,也不会在浏览器控制台中看到“表单数据”部分。

这就是我要的 :

出现在浏览器控制台中的表单数据条目

但是我的电话看起来像这样:

没有表单数据部分的呼叫

这是我当前的代码( component.ts ):

  public picture: FormData;

  addedImage(event) {
    this.picture = event.addedFiles[0];
    console.log(this.picture);
    this.api.uploadFile(this.picture).subscribe();
  }

...以及api部分( apis.ts ):

 public uploadFile(file){
    const url = AppGlobal.API_URL + 'provisioning/api/files';
    let httpParams = new HttpHeaders();
    httpParams = httpParams.set('Content-Type', 'multipart/form-data');
    console.log(httpParams);
    return this.http.post<any>(url, file, {headers: httpParams}).pipe(
      map((data: any) => {
        console.log('return ', data);
          if(data) this.s.latestFileId$.next(data);
        }
      ));
  }

这是上述component.ts中console.log输出的内容:

File {name: "image.jpg", lastModified: 1568824078958, lastModifiedDate: Wed Sep 18 2019 18:27:58 GMT+0200 (Central European Summer Time), webkitRelativePath: "", size: 69192, …}
lastModified: 1568824078958
lastModifiedDate: Wed Sep 18 2019 18:27:58 GMT+0200 (Central European Summer Time) {}
name: "image.jpg"
size: 69192
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
api.calls.ts:41 

...以及apis.ts中的console.log

HttpHeaders {normalizedNames: Map(0), lazyUpdate: Array(1), headers: Map(0), lazyInit: HttpHeaders}
headers: Map(0)
size: (...)
__proto__: Map
[[Entries]]: Array(0)
length: 0
lazyInit: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
lazyUpdate: [{…}]
normalizedNames: Map(0) {}
__proto__: Object

我究竟做错了什么?

这是我尝试过的另一个错误语法( component.ts ):

  addedImage(event) {
    var oOutput = document.querySelector("div"), oData = new FormData();
    oData.append("myfile", event.addedFiles[0], "filename.txt");
    this.picture = event.addedFiles[0];
    console.log(this.picture);
    this.api.uploadFile(oOutput);
  }

apis.ts ):

  public uploadFile(file){
    const url = AppGlobal.API_URL + 'provisioning/api/files';
    const oReq = new XMLHttpRequest();
    oReq.open('POST', url, true);
    oReq.onload = function(oEvent) {
      if (oReq.status == 200) {
        console.log('upload success');
      } else {
        console.log('upload fail');
      }
    };

    oReq.send(file);
  }

使用FormData API

const formData: FormData = new FormData();
formData.append('files[]', event.addedFiles[0]);
let httpParams = new HttpHeaders();
httpParams = httpParams.set('Accept', '*/*');
this.http.post('some/url', formData, {headers: httpParams})

您也可以参考本指南 但是,这不是特定于Angular的。

尝试这个:

constructor(private http: Http) {}
private baseUrl = "api/sth";

private sendData():observable<any>{
    const formData: FormData = new FormData();
    formData.append(key, value);

    const headers = new Headers();
    headers.append("Accept", "application/json");
    const options = new RequestOptions({ headers: headers });

    return this.http
        .post(`${this.baseUrl}/url`, formData, options)
        .catch(this.handleError);
}


private handleError(error: Response): Observable <any> {
    console.error("observable error: ", error);
    return Observable.throw(error.statusText);
}

如果您想通过formData将图像发送到服务器,请访问此

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM