42

我需要上传一个文件并发送一些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

4 回答 4

29

模板:

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

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 库 - 在 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
                )
            });
    }
}
于 2017-01-19T13:39:48.320 回答
12

这是Angular2 Git Repository上的一个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中上传文件

从输入类型=文件上传Angular 2文件

Angular2发布上传的文件

于 2016-05-12T04:53:47.103 回答
5

我知道这已被标记为已回答并且已经很老了,但是我在将 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;
    }

}
于 2017-01-18T17:20:21.037 回答
1

我解决了这个问题,根本不需要content-type

见这里,https://stackoverflow.com/a/45879409/2803344

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

2017.8.25

于 2017-08-25T10:35:17.983 回答