简体   繁体   English

如何在 Fetch API 上将带有输入文件的数组发送到 PHP

[英]How to send a array with input file to PHP on Fetch API

I have one form in HTML我有一个 HTML 表单

HTML 表单

I have a fetch AJAX and I can send more than one form in a request to return just one alert message.我有一个fetch AJAX,我可以在请求中发送多个表单以仅返回一条警报消息。

const has = document.querySelectorAll('.main_app_form_edit');

if (has) {
    const newFormData = (new FormData());

    newFormData.append('_token', document.querySelector('input[name="_token"]').value);

    let i = 0;
    document.querySelector('.test_submit')
        .addEventListener('click', (e) => {
            e.preventDefault();

            const formCards = document.querySelectorAll('.main_app_form_edit');

            const url = formCards[0].getAttribute('action');
            const method = formCards[0].getAttribute('method');

            for (element of formCards) {
                const formConst = (new FormData(element));

                // BEGIN FILE
                const file = element[3].files[0];

                const newObject = {
                    'tmp_name': file.mozFullPath,
                    'lastModifiedDate': file.lastModifiedDate,
                    'name': file.name,
                    'size': file.size,
                    'type': file.type
                };

                formConst.append('img', (new URLSearchParams(newObject)).toString());
                formConst.delete('image');
                // END FILE

                newFormData.append(
                    'data_' + ++i,
                    JSON.stringify((new URLSearchParams(formConst)).toString())
                );
            }

            getCards(method, url, 'multipart/form-data', newFormData);
    });
}

In Laravel, when I try to get the file, I don't have a form to read the img array as a file, because I don't have a fullPath and when I tried to use monFullPath , it did not work:在 Laravel 中,当我尝试获取文件时,我没有将img数组作为文件读取的表单,因为我没有fullPath并且当我尝试使用monFullPath时,它不起作用:

public static function createCardsPost(Request $request)
{
    $forms = $request->except(['_token', 'img']);

    foreach ($forms as $form) {
        // PARSEANDO OS DADOS QUE DEVEM SER PARSEADOS
        parse_str($form, $dataArray);
        parse_str($dataArray['img'], $img);

        $dataArray['img'] = (array)$img;

        $requestArray = new Request($dataArray);
        $dataArray = $requestArray->except(['"_token']);

        $dataArray['user_id'] = 1;
        $dataArray['folder_id'] = 1;

        if ($requestArray->hasFile('img') && $requestArray->img->isValid()) {
            $dataArray['img'] = $requestArray->file('img')->store('/cards');
        }

        var_dump($dataArray);
        die();

        \App\Card::create($dataArray);
    }

    header('Content-Type: application/json');

    $callback['message'] = 'Pasta e cartões cadastrados com sucesso!';
    
    return json_encode($callback);
}

How do I do that?我怎么做? How do I send a file array with a valid format to PHP?如何向 PHP 发送具有有效格式的文件数组?

PHP转储

I resolve that, solution:我解决了,解决方案:

Yesterday, I created a solution.昨天,我创建了一个解决方案。 I pass a unique identifier for the index file to your data set.我将索引文件的唯一标识符传递给您的数据集。 Then I can find out which one is in which dataset.然后我可以找出哪个在哪个数据集中。

ex : [[arrayDataSet_300], [FormDataFile_300000]]例如:[[arrayDataSet_300]、[FormDataFile_300000]]

I multiply the index for 1000 (100 * 1000) then I can send to Laravel more than one data set with a file with a valid format我将索引乘以 1000 (100 * 1000),然后我可以向 Laravel 发送多个数据集以及一个具有有效格式的文件

// REGRA DE NEGÓCIO DOS CARDS
    const createCards = async (folderId) => {
        if (typeof folderId !== 'number') {
            alert('Não foi possível cadastrar. Volte mais tarde!');
            throw new Error({'folder_id': folderId});
        }
        const newFormData = new FormData();
        const formCards = document.querySelectorAll('.main_app_form_edit');
        const url = formCards[0].getAttribute('action');
        const method = formCards[0].getAttribute('method');
        let i = 1;
        for (element of formCards) {
            ++i;
            const formData = (new FormData(element));
            formData.append('folder_id', folderId);
            const file = element[3].files[0];
            newFormData.append((i * 1000), file);
            newFormData.append(i, (new URLSearchParams(formData)));
        }
    
        newFormData.append('_token', document.querySelector('input[name="_token"]').value)
        getCards(method, url, 'multipart/form-data', newFormData);
    }
    // FIM DA REGRA DE NEGÓCIO DOS CARDS

php laravel side: php laravel 方面:

 public static function createCardsPost(Request $request)
    {
        $forms = $request->except(['_token']);
        for ($i = 2; $i <= (count($forms) !== 2 ? count($forms) - 2 : 2); $i++) {
            // PARSEANDO OS DADOS QUE DEVEM SER PARSEADOS
            parse_str($forms[$i], $dataArray);

            $requestArray = new Request($dataArray);
            $dataArray = $requestArray->except(['_token', 'image']);

            /** -test--id- */
            $dataArray['user_id'] = 1;
            /** ---------- */
            // ID DE RETORNO
            $hrefId = $dataArray['folder_id'];

            // SALVA O ARQUIVO SE HOUVER
            $dataArray['img'] = Folder::saveFolder(((empty($forms[$i * 1000]) ? $forms[$i * 1000] : null)));

            \App\Card::create($dataArray);
        }

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

相关问题 获取 Api - 如何将 PHP SESSION 数据发送到目标 Z2FEC392304A5C23AC138DA27 文件? - Fetch Api - how to send PHP SESSION data to the target PHP file? 使用fetch api发送带有图像的数据,但文件数组为空php - Send data with images using fetch api but array of files is empty php 如何在 PHP 中向通过 javascript fetch API 发出的请求发送响应? - How to send a response in PHP to a request made through the javascript fetch API? 如何使用 fetch 通过 api 发送文件元数据 - How to send file metadata over api using fetch 如何将Javascript数组和表单输入发送到PHP文件(例如,通过$ _GET)? - How to send a Javascript Array and Form Input to PHP File (via $_GET for example)? 如何将图像从输入转换为 json,将其发送到 php,然后通过 PHPMailer 将其发送到服务器上? - How to convert an image from input to json, send it in fetch to php and then send it on server via PHPMailer? 如何使用Fetch API从输入元素提交文件 - How to submit a file using Fetch API from an input element 使用 javascript 将数据发送到 json 文件 fetch api - send data to json file with javascript fetch api 发送文件到(获取到 c# web api) - Send file to (fetch to c# web api) 尝试发送请求时出现“ 405方法不允许”错误。 通过JS提取API到PHP文件 - “405 Method Not Allowed” error while trying to send req. via JS fetch API to PHP file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM