简体   繁体   English

VueJS - 如何发送 JSON 数组的 POST 请求,每个数组除了每个数组元素的文件或图片之外还包括数据

[英]VueJS - How to send a POST request of a JSON array each including data in addition to a File or Picture for each array element

I'm trying to send through Axios to PHP formData from a dynamic Form where a user can add as many "persons" as he wants.我正在尝试通过 Axios 将动态表单中的 PHP formData 发送到用户可以根据需要添加任意数量的“人员”。 Each person has data + a picture.每个人都有数据+一张图片。

Here's the data format这是数据格式

data: {
    person:{
        personname: '',
        securitynumber: '',
        dob: '',
        picture: '',
    },
    persons: [],
},

Everything works without the picture, I'm able to upload images by creating a FormData, but how is it possible to change the whole data array (persons) to JSON with each element having its own picture file.没有图片一切正常,我可以通过创建 FormData 上传图像,但是如何将整个数据数组(人)更改为 JSON,每个元素都有自己的图片文件。

On submit i'm appending to the formData在提交时,我将附加到 formData

 var formData = new FormData();

        Object.keys(this.persons).forEach(key => {
            formData.append(key, JSON.stringify(this.persons[key]));
        });

However, i'm having trouble adding a file(picture) specifically to each person item in the array.但是,我无法专门为数组中的每个人项添加文件(图片)。 (fetching it from the form input with ref and having it be part of the form data JSON). (使用 ref 从表单输入中获取它,并将其作为表单数据 JSON 的一部分)。

Thank you for any input.感谢您的任何意见。

I was able to make it work by ditching the ref idea and working with an onChange that takes the elements as such:我能够通过放弃 ref 想法并使用 onChange 来使其工作,该 onChange 采用以下元素:

In the form loop:在表单循环中:

<input class="form-control-file" :id="'file-'+index" type="file" accept="image/*"
                                               @change="onFileChange(person, $event)">

Vues function: Vues function:

onFileChange(item, e) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
            return;
        this.createImage(item, files[0]);
    },
    createImage(item, file) {
        var image = new Image();
        var reader = new FileReader();

        reader.onload = (e) => {
            item.image = e.target.result;
        };
        reader.readAsDataURL(file);
    },

That way, for every form element (vue array element), i'm able to assign an image.这样,对于每个表单元素(vue 数组元素),我都可以分配一个图像。 The result is a formData that includes all the array elements easily posted to PHP.结果是一个 formData,其中包含所有易于发布到 PHP 的数组元素。

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

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