简体   繁体   中英

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

I have one form in HTML

HTML 表单

I have a fetch AJAX and I can send more than one form in a request to return just one alert message.

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:

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转储

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]]

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

// 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:

 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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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