typescript-如何在Angular 2中发布FormData对象?

我需要上传一个文件并发送一些json,我有这个功能:

POST_formData(url, data) {
        var headers = new Headers(), authtoken = localStorage.getItem('authtoken');

        if (authtoken) {
            headers.append("Authorization", 'Token ' + authtoken)
        }

        headers.append("Accept", 'application/json');
        headers.delete("Content-Type");

        var requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: this.apiURL + url,
            headers: headers,
            body: data
        })

        return this.http.request(new Request(requestoptions))

        .map((res: Response) => {
            if (res) {
                return { status: res.status, json: res.json() }
            }
        })
    }

我的问题是,如果我将content-type设置为“ multipart/form-data”,我的服务器会抱怨边界,如果我完全删除content-type标头,我的服务器会抱怨它“ text/plain”是受支持的媒体类型。

那么,如何发送带有angular2的FormData?

4个解决方案
29 votes

模板:

<label class="btn btn-primary">
  <input type="file" style="display: none;" multiple="true" (change)="fileChange($event)" accept=".xml">
  <span>Click Me!</span>
</label>

UPD:Angular 5-HttpClient +打字稿

onFileUpload(event: EventTarget) {

  const eventObj: MSInputMethodContext = <MSInputMethodContext>event;
  const target: HTMLInputElement = <HTMLInputElement>eventObj.target;
  const files: FileList = target.files;

  const formData: FormData = new FormData();

  for (let i = 0; i < files.length; i++) {
    formData.append('file', files[i]);
  }

  // POST
  this.httpClient.post<AnalyzedData>(uploadUrl, formData).subscribe(...);
}

旧的Http lib-Angular 4.3之前的版本:

fileChange(event) {
    let files = event.target.files;
        if (files.length > 0) {
        let formData: FormData = new FormData();
        for (let file of files) {
             formData.append('files', file, file.name);
        }
        let headers = new Headers();
        headers.set('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(uploadURL, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
            data => {
                // Consume Files
                // ..
                console.log('uploaded and processed files');
            },
            error => console.log(error),
            () => {
                this.sleep(1000).then(() =>
                    // .. Post Upload Delayed Action
                )
            });
    }
}
Dhruvan Ganesh answered 2020-08-10T11:01:23Z
12 votes

这是Angular2 Git存储库上的Open Isuue,并且还有一个Pull Request正在等待合并,希望它会尽快合并。


或者,

为此,您可以直接使用XMLHttpRequest对象。

并且不要忘记设置标题

xhr.setRequestHeader("enctype", "multipart/form-data");

// IE workaround for Cache issues
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Cache-Control", "no-store");
xhr.setRequestHeader("Pragma", "no-cache");

在您制作的XMLHttpRequest上。


类似问题:

如何在Angular2中上传文件

从输入类型=文件上传角度2文件

Angular2发布上传的文件

Ankit Singh answered 2020-08-10T11:00:55Z
5 votes

我知道这已经被标记为已回答并且已经很旧了,但是我在将FormData对象发布到OpenIdConnect AuthServer时遇到了问题,上面的文件上传示例不是我想要的。

这是我获得OpenIdAuthToken的服务:

import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, URLSearchParams} from '@angular/http'
import { OpenIdTokenRequest, SmartData } from '../model/openid-token-request';
import { OpenIdToken } from '../model/openid-token';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Observable } from 'rxjs';

@Injectable()

export class TokenService {

    constructor(private _http: Http) { }

    getToken(requestData: OpenIdTokenRequest, smartData: SmartData) {
        let _urlParams = new URLSearchParams();
        _urlParams.append('code', requestData.code);
        _urlParams.append('grant_type', requestData.grantType);
        _urlParams.append('redirect_uri', requestData.redirectUri);
        _urlParams.append('client_id', requestData.clientId);

        let _url = smartData.tokenUri;
        let _options = this.getTokenPostOptions();

        return this._http.post(_url, _urlParams, _options)
            .map(response => <OpenIdToken>response.json())
    }

    private getTokenPostOptions(): RequestOptions {

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
        let options = new RequestOptions({ headers: headers });

        return options;
    }

}
cobolstinks answered 2020-08-10T11:01:48Z
1 votes

我解决了这个问题,根本不需要headers

看到这里,[https://stackoverflow.com/a/45879409/2803344]

另请参阅此处以检查如何设置Angular2的headers-为每个请求设置标头

2017.8.25

Belter answered 2020-08-10T11:02:21Z
translate from https://stackoverflow.com:/questions/37174759/how-do-you-post-a-formdata-object-in-angular-2