薇晓朵技术论坛 版块列表 WordPress 插件 Gravity Forms Gravity Forms 使用上传文件的功能无法上传 ico 格式的文件

标签: 

正在查看 2 帖子:1-2 (共 2 个帖子)
  • 作者
    帖子
  • changhongshan
    参与者
      @changhongshan
      文章数量:16

      Gravity Forms中使用File Upload字段,并勾选Enable Multi-File Upload选项之后,使用js就不能再读取到输入框的files了,那么我该如何把文件存到formdata里面请求自己的接口呢

      壳壳虫
      参与者
        @kekechong
        文章数量:265

        对于第一个问题,Gravity Forms默认只允许上传特定的文件类型,包括常见的图像、文档和音频/视频文件。如果你想允许上传ico格式的文件,你需要在Gravity Forms的设置中添加ico文件类型的支持。你可以通过在functions.php文件中添加以下代码来实现:

        add_filter( 'gform_upload_mimes', 'add_custom_upload_mimes' );
        function add_custom_upload_mimes( $mimes ) {
            $mimes['ico'] = 'image/x-icon';
            return $mimes;
        }

        对于第二个问题,当勾选了”Enable Multi-File Upload”选项后,Gravity Forms会使用自己的方式处理文件上传,这可能导致无法直接通过JavaScript读取输入框的files属性。如果你想将文件存储到FormData中并发送到自己的接口,你可以使用Gravity Forms的gform_after_submission钩子来实现。在你的主题的functions.php文件中添加以下代码:

        add_action( 'gform_after_submission', 'upload_files_to_custom_api', 10, 2 );
        function upload_files_to_custom_api( $entry, $form ) {
            $file_ids = explode( ',', rgar( $entry, 'fileupload_field_id' ) ); // 替换fileupload_field_id为你的文件上传字段ID
            $files = array();
        
            foreach ( $file_ids as $file_id ) {
                $file_path = get_attached_file( $file_id );
                $file_name = basename( $file_path );
                $file_type = wp_check_filetype( $file_name )['type'];
        
                $files[] = array(
                    'name'     => $file_name,
                    'type'     => $file_type,
                    'tmp_name' => $file_path,
                    'error'    => 0,
                    'size'     => filesize( $file_path ),
                );
            }
        
            $api_url = 'http://your-api-url.com'; // 替换为你的自定义接口URL
            $request = wp_remote_post( $api_url, array(
                'method'      => 'POST',
                'timeout'     => 45,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking'    => true,
                'headers'     => array(),
                'body'        => array(
                    'files' => $files,
                ),
                'cookies'     => array(),
            ) );
        
            if ( is_wp_error( $request ) ) {
                // 处理请求错误
            } else {
                $response_code = wp_remote_retrieve_response_code( $request );
                $response_body = wp_remote_retrieve_body( $request );
        
                // 处理请求响应
            }
        }

        在上面的代码中,你需要将fileupload_field_id替换为你的文件上传字段的ID,并将http://your-api-url.com替换为你的自定义接口的URL。当用户提交表单时,该代码将在后台将文件上传到你的自定义接口,并返回响应。你可以根据需要处理请求和响应的逻辑。


        以上由壳壳虫自动解答供参考,您可以继续跟帖或等待人工回复。

      正在查看 2 帖子:1-2 (共 2 个帖子)

      抱歉,回复话题必需登录。