你如何在 Angular 2 中发布一个 FormData 对象? [英] How do you POST a FormData object in Angular 2?

查看:23
本文介绍了你如何在 Angular 2 中发布一个 FormData 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to upload a file and send some json along with it, I have this function:

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"支持的媒体类型.

My issue is, if I set the content-type to "multipart/form-data" my server complains about the boundaries, if I remove the content-type header completely, my server complains that it "text/plain" a supported media type.

那么,如何使用 angular2 发送 FormData?

So, how do you send FormData with angular2?

推荐答案

这是一个Open Isuue on Angular2 Git Repository,还有一个Pull Request 等待合并,希望早日合并.

It's an Open Isuue on Angular2 Git Repository, and there is also a Pull Request waiting to be merged, hope that it will be merged soon.

或者,

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

You can use XMLHttpRequest Object directly, for that.

不要忘记设置标题

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 中上传文件

从输入 type=file 上传 Angular 2 文件

Angular2 发布上传的文件

这篇关于你如何在 Angular 2 中发布一个 FormData 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆