简体   繁体   English

无法使用 Axios 使用 FormData 使用 Vue.js 发送字符串

[英]Unable to send strings with Axios using FormData using Vue.js

I'm trying to send an input of file along with an input of text in a single request using Axios and FormData in Vue.js.我正在尝试使用 Vue.js 中的 Axios 和 FormData 在单个请求中发送文件输入和文本输入。 I've read that it is very simple, just do:我读过这很简单,只需执行以下操作:

const formData = new FormData();
formData.append('file', file);
formData.append('text', text);
axios.post('ajax.php', formData)
.then(function (response){
    console.log(response.data);
})

But that only works for some absurd reason if “text” is an integer.但这仅在“文本”是 integer 时出于某些荒谬的原因才有效。 This is the HTML code that I'm using for the form:这是我用于表单的 HTML 代码:

<div v-for="(gallery, i) in galleryMeta">
    <form @submit.prevent="editData('gallery', gallery.Id, i)">
        <div class="row no-gutters">
            <div class="col-xl-6 col-md-5 col-sm-4 col-12 pb-sm-0 pt-sm-0 d-flex align-items-center justify-content-md-start justify-content-sm-center">
                <div class="d-flex flex-column py-3 pl-sm-0 pl-4">
                    <h6 class="font-normal text-brand-primary pb-1 pl-md-0 pl-sm-4">Title:</h6>
                    <div class="d-flex justify-content-md-start justify-content-sm-center">
                        <input type="text" class="border-radius d-md-flex d-sm-none" v-model="gallery.Title">
                        <input type="text" class="border-radius w-75 d-md-none d-sm-flex d-none" v-model="gallery.Title">
                    </div>
                </div>
            </div>
            <div class="col-md-2 col-sm-3 col-12 pb-sm-0 d-flex align-items-center justify-content-sm-end justify-content-center">
                <div class="d-flex flex-sm-column pr-lg-0 pr-sm-3">
                    <label class="btn btn-brand-primary font-bold py-2 my-sm-0 my-2" for="file">EDIT</label>
                    <input type="file" id="file" ref="file" style="display: none;" accept="image/jpeg,image/png,image/webp" @change="pickData">
                    <button class="btn btn-brand-secondary font-bold px-lg-5 px-3 py-2 my-2 mx-sm-0 mx-2" @click="editData('gallery', gallery.Id, i)">UPLOAD</button>
                </div>
            </div>
        </div>
    </form>
</div>

The form works just fine for everything else.该表格适用于其他所有内容。 This is the Vue.js code:这是 Vue.js 代码:

let app = Vue.createApp({
    data: function(){
        return{
            File: '',
        }
    },
    methods:{
        pickData: function (){
            this.File = event.target.files[0];
        },
        editData: function (requestSection, Id, i, Title){
            if(requestSection === 'gallery'){
                const formData = new FormData();
                formData.append('file', this.File);
                formData.append('id', Id);
                formData.append('title', this.galleryMeta[i].Title);
                axios.post('ajax.php', formData, {
                    header: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                .then(function (response){
                    console.log(response.data);
            }
        }
    }
})

This is the ajax.php file to handle the Axios AJAX request:这是处理 Axios ZA34A6659BCEAE779F28185E757 请求的 ajax.php 文件:

<?php
$data = json_decode(file_get_contents("php://input"));
$request = $data->request;

if(isset($_FILES['file']['name'])){
    $id = json_decode($_POST['id']);
    $title = json_decode($_POST['title']);
    $file = file_get_contents($_FILES['file']['tmp_name']);
}
?>

You may've noticed the 2 first lines in the PHP code.您可能已经注意到 PHP 代码中的前 2 行。 The reason for why they're there is that in the same PHP file I'm also handling other simple Axios POSTS requests by data binding, which all work properly.它们存在的原因是在同一个 PHP 文件中,我还通过数据绑定处理其他简单的 Axios POSTS 请求,这些请求都可以正常工作。 Although I believe that they do not cause any issues related to this, I'm including them just in case they do.尽管我相信它们不会引起与此相关的任何问题,但我将它们包括在内以防万一。

In the PHP file $id is defined properly, $file is defined properly however $title never is no matter what I do.在 PHP 文件中$id定义正确, $file定义正确但是$title无论我做什么都不会。 After hours of intense troubleshooting, I've found that strings never make it past the Axios request, ever.经过数小时的密集故障排除后,我发现字符串永远不会超过 Axios 请求。 If I change:如果我改变:

formData.append('title', this.galleryMeta[i].Title);

to

formData.append('title', '20');

It is immediately sent properly.它会立即正确发送。 The problem is not in the galleryMeta array of objects if I set the Title in galleryMeta to a random number everything works.如果我将galleryMeta中的Title设置为随机数,则问题不在galleryMeta对象数组中,一切正常。 All the variables that I'm using in the JavaScript code are properly defined.我在 JavaScript 代码中使用的所有变量都已正确定义。 I tried to console.log() every single bit of that code, and all the variables contain their respective proper expected values, always.我试图 console.log() 该代码的每一位,并且所有变量始终包含它们各自正确的预期值。 But strings never get parsed by Axios AJAX at all.但是字符串永远不会被 Axios AJAX 解析。 It doesn't matter how long the string is or what does it contain, it just won't get past the request.不管字符串有多长或它包含什么,它都不会超过请求。 I've also checked the values of that formData form with this loop:我还用这个循环检查了formData表单的值:

for (var value of formData.values()) {
   console.log(value); 
}

And they're all there, assigned properly, just like I wanted.他们都在那里,正确分配,就像我想要的那样。 So my question is pretty obvious.所以我的问题很明显。 How the hell do I parse strings using FormData with Axios in Vue.js?我到底如何在 Vue.js 中使用带有 Axios 的 FormData 解析字符串? What have I done wrong to make this happen?我做错了什么让这件事发生? God, thank anybody who can point out the issue in this.上帝,感谢任何能指出这个问题的人。 Thank you!谢谢!

$id = json_decode($_POST['id']);

It works if it is an integer because an integer is valid JSON.如果它是 integer,它就可以工作,因为 integer 是有效的 JSON。

It would also work if the string you were sending was null , false , "foo" (yes, with the quotes), or any other valid JSON.如果您发送的字符串是nullfalse"foo" (是的,带引号)或任何其他有效的 JSON,它也可以工作。

You are sending a FormData object which serializes to a multipart/form-data request body.您正在发送一个 FormData object ,它序列化为一个 multipart/form-data 请求正文。 This is not JSON这不是 JSON

Do not try to process it as JSON.不要尝试将其处理为 JSON。

Do not use file_get_contents("php://input") ;不要使用file_get_contents("php://input") Do use $_POST and $_FILES一定使用$_POST$_FILES

Do not use json_decode ;不要使用json_decode Do just use the values from $_POST and $_FILES只使用来自$_POST$_FILES的值


Aside : Do not specify 'Content-Type': 'multipart/form-data' as this is missing the mandatory boundary parameter.另外不要指定'Content-Type': 'multipart/form-data'因为这缺少强制boundary参数。 The browser will add the right Content-Type header automatically when it receives the FormData object.浏览器在收到FormData object时会自动添加正确的Content-Type header。

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

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