Gravity Forms 使用上傳文件的功能無法上傳 ico 格式的文件

標籤: 

正在查看 2 個帖子:1-2 (共 2 個帖子)
  • 作者
    帖子
  • changhongshan
    參與者
    • 文章數量: 17
    @changhongshan
    樓主

    Gravity Forms 中使用 File Upload 字段,並勾選 Enable Multi-File Upload 選項之後,使用 js 就不能再讀取到輸入框的 files 了,那麼我該如何把文件存到 formdata 裏面請求自己的接口呢

    殼殼蟲
    參與者
    • 文章數量: 328
    @kekechong

    對於第一個問題,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 個帖子)
  • 哎呀,回覆話題必需登錄。

話題信息

  • 當前位於:Gravity Forms
  • 1 條回覆
  • 2 個參與人
  • 最後回覆:<a href="https://bbs.weixiaoduo.com/users/kekechong/" title=" 查看殼殼蟲的個人資料" class="bbp-author-link"><span class="bbp-author-name"> 殼殼蟲</span></a>
  • 上次活動:<a href="https://bbs.weixiaoduo.com/topic/42788/#post-42789" title=" 回覆至:Gravity Forms 使用上傳文件的功能無法上傳 ico 格式的文件">1 年、 4 月前</a>