为了账号安全,请及时绑定邮箱和手机立即绑定

如何在提交事件之间持久化文件上传表单数据

如何在提交事件之间持久化文件上传表单数据

PHP
天涯尽头无女友 2022-06-17 09:55:59
我试图在更改其他表单切换/参数时保留上传的文件信息,并避免每次都重新上传文件。是否可以保留文件上传数据?表单的 HTML<form method="POST" action="" enctype="multipart/form-data"><input type="file" name="fileUpload" id="fileUpload"><input type="submit" value="Upload This" name="upload"><input type="submit" value="Preview" name="preview"><div class="col text-center justify-content-center"><div class="bmd-form-group"><label class="bmd-label-static" for="txtcolor">Choose the Text Color</label><input type="color" id="txtcolor" name="txtcolor" value="#000000"><label for="body">Body</label></div></div><div class="col text-center justify-content-center"><div class="form-check"><label class="form-check-label"><input id="iversion" class="form-check-input" name="invertBox" type="checkbox" value="">Invert<span class="form-check-sign"><span class="check"></span></span></label></div></div><?phpif($previewOk){    echo "<img class='w-100 h-100' src='data:image/jpeg;base64, $imgData'  />"; ?><?php } ?><a href="<?php $add_to_cart = do_shortcode('[add_to_cart_url id="'.$post->ID.'"]'); echo $add_to_cart;?>"class="more">Buy now</a></form>PHP$previewOk=0;if($_FILES["fileUpload"]["tmp_name"]){    $myfile=$_FILES["fileUpload"]["tmp_name"];}if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){    $file_url = move_file_test(); //moves file to directory    $theid = create_download(); //creates a file link    create_download_version($theid, $file_url); //more file stuff}if(isset($_POST['txtcolor'])){    $color = $_POST['txtcolor'];    $myfile = change_color($myfile); //some function that alters the $myfile and regenenerates}if(isset($_POST["preview"])) {    $imgData = base64_encode(file_get_contents($myfile));    previewOk = 1;}我想$myfile在提交表单后留下来,只在上传不同的文件时更新。目的是$myfile再次以其他基于表单的操作进行访问 - 例如:更改上传的图像文件的背景颜色并预览它,而无需启动文件浏览器并重新开始每次迭代。
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

您可以使用 ajax 来选择是否将文件与其他字段一起发送。会话可用于在请求之间保留 file_url。


我在下面给你一个算法,如何组织一切。


HTML


<form id="form-id" method="POST" action="" enctype="multipart/form-data">

    <input type="file" name="fileUpload" id="fileUpload">

    <div class="col text-center justify-content-center">

        <div class="bmd-form-group">

            <label class="bmd-label-static" for="txtcolor">Choose the Text Color</label>

            <input type="color" id="txtcolor" name="txtcolor" value="#000000">

            <label for="body">Body</label>

        </div>

    </div>

    <div class="col text-center justify-content-center">

        <div class="form-check">

            <label class="form-check-label">

                <input id="iversion" class="form-check-input" name="invertBox" type="checkbox" value="">Invert <span class="form-check-sign">

<span class="check"></span> </span>

            </label>

        </div>

    </div>

    <input type="submit" id="submit" name="submit" value="Submit">

    <div id="preview"></div>

    <div id="add_to_cart"></div>

</form>

Javascript


jQuery( document ).ready(function( $ ) { 


    // Prevent form submission

    $('#form-id').on( "submit", function( event ) {

        event.preventDefault();

    });


    // Handle file selection and upload

    $('#fileUpload').on("change", function() {


        var files = this.files;

        if (!files.length) return;


        var file = files[0];


        var data = new FormData();

        data.append( 'action', 'upload' );

        data.append( 'nonce', window.wp_data.nonce );

        data.append( 'file', file );

        $.ajax({

            url: window.wp_data.ajax_url,

            type: 'POST', 

            data: data,

            cache: false,

            dataType: 'json',

            processData: false,

            contentType: false,

            success: function( respond, status, jqXHR ){

                if( typeof respond.error === 'undefined' ){

                    $('#preview').html( respond.data.preview );

                    $('#add_to_cart').html( respond.data.add_to_cart );

                }

            },

            error: function( jqXHR, status, errorThrown ){

                console.log( 'AJAX requert error: ', status, jqXHR );

            }

        })

    });


    // Processing other fields on Submit button click. This is a case if you have to process many fields.

    $('#submit').on( "click", function( event ) {

        var data = { 

            action: 'process',

            nonce: window.wp_data.nonce

        };

        $.each(

            $('#form_id').serializeArray(), 

            function (i, field) { 

                if (data[field.name]) {

                    if (!data[field.name].push) {

                        data[field.name] = [data[field.name]];

                    }

                    data[field.name].push(field.value || '');

                } else {

                    data[field.name] = field.value || '';

                }

            }

        );

        $.post( 

            window.wp_data.ajax_url,

            data,

            function( respond ) {

                $('#preview').html( respond.data.preview );

                $('#add_to_cart').html( respond.data.add_to_cart );

            }, 

            "json"

        )

    });

});

PHP


// This is an idea how to store uploaded file_url: use session vars

add_action( 'init', function () {

    if( !session_id() ) {

        session_start();

    }

}, 1);


// A trick to use nice wordpress ajax hooks at frontend

add_action( 'wp_head', function () {

    $variables = array (

        'ajax_url' => admin_url('admin-ajax.php'), // Pass ajax_url to frontend

        'nonce' => wp_create_nonce('my-nonce') // Security

    );

    echo(

        '<script type="text/javascript">window.wp_data = ' .

        json_encode($variables) .

        ';</script>'

    );

} );


// Handle upload request

add_action( 'wp_ajax_upload', function () {

    check_ajax_referer( 'my-nonce', 'nonce' ); // Check security


    $data = [];

    if ( isset( $_FILES['fileUpload'] ) and !$_FILES['fileUpload']['error'] ) {

        $file_url = save_file_to_directory();

        #_SESSION['file_url'] = $file_url; // Save file_url to session for future use


        $data['preview'] = generate_preview( $file_url );

        $data['add_to_cart'] = generate_add_to_cart();


        wp_send_json_success( $data );

    }

    else {

        wp_send_json_error();

    }

    wp_die();

} );


// Handle fields request. I separate it for better understanding. You may merge this logic with wp_ajax_upload. 

add_action( 'wp_ajax_process', function () {

    check_ajax_referer( 'my-nonce', 'nonce' ); // Check security


    $file_url = #_SESSION['file_url']; // Remember $file_url from session


    $data = [];

    if ( isset( $_REQUEST['txtcolor'] ) ) {

        $data['preview'] = apply_txtcolor( $file_url );

        $data['add_to_cart'] = generate_add_to_cart();

    }

    if ( isset( $_REQUEST['invertBox'] ) ) {

        $data['preview'] = apply_invertBox( $file_url );

        $data['add_to_cart'] = generate_add_to_cart();

    }


    wp_send_json_success( $data );

    wp_die();

} );

根据情况,某些时刻可以做得更好或不同的方式。这只是算法的思想。请记住在适当的时候删除图像文件,以防您不再需要它。


查看完整回答
反对 回复 2022-06-17
  • 1 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信