在Angular 4中上传文件并将其传递给php文件 [英] Upload file in Angular 4 and pass it to php file

查看:26
本文介绍了在Angular 4中上传文件并将其传递给php文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 var_dumb() 读取文件对象为空的数据时,我正在尝试在 Angular 4 中上传文件并将其与另一个数据(如文本)一起发送到 php.

我的post.component.html:

它可以通过 base64 解决,但这不是我的选择,请问有什么想法吗?

解决方案

希望能帮到你,如何在 Angular 2+ 中发送表单数据:

 import {HttpClient, HttpHeaders} from '@angular/common/http';...构造函数(私有 http:HttpClient){}...测试() {const formData = new FormData();formData.append('数据', JSON.stringify({测试一下'}));formData.append('文件', 文件);const headers = new HttpHeaders().set('Content-Type', []);//IE 需要 responseType 'text'返回 this.http.post(url, formData, {标题,响应类型:'文本'});}

I'm trying to upload file in Angular 4 and send it to php with another data like text, when I use var_dumb() to read the data the File Object empty.

My post.component.html:

<a class="upload-photo-item">
            <input type="file" class="Upload-photo" accept="image/*" ngf-max-size="2MB" (change)="handleInputChange($event)"/>
            <i class="fa fa-tags olymp-computer-icon" aria-hidden="true"></i>

            <h6>Upload Photo</h6>
            <span>Browse your computer.</span>
        </a>

And this is handleInputChange function:

    post = new PostObject();
    image: File;

 handleInputChange(event) {
        console.log(event);
        this.image = event.target.files[0];

        var pattern = /image-*/;

        if (!this.image.type.match(pattern)) {
            console.log('File is not an image');
            return;
        }
        this.post.postPhoto = this.image;

        console.log('image :' + this.image);
  }

Everything until now is perfect, I can see my Object file in console, Now here is the problem:

My post.php:

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
exit;

The API response with array(0) like this:

It can be solved by base64 but this is not an option for me, any ideas please?

解决方案

Hope this helps, how to send formdata in Angular 2+:

    import {HttpClient, HttpHeaders} from '@angular/common/http';
    ...
    constructor(private http: HttpClient) {}
    ...
    test() {
            const formData = new FormData();
            formData.append('data', JSON.stringify({
                test: 'test'
            }));
            formData.append('file', file);

            const headers = new HttpHeaders().set('Content-Type', []);

            // responseType 'text' is necessary for IE
            return this.http.post(url, formData, {
                headers,
                responseType: 'text'
            });
    }

这篇关于在Angular 4中上传文件并将其传递给php文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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