You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP对接Telegram机器人表单:文件超50KB无法提交求助

问题分析与解决方案

你的前端AJAX代码没有明显错误,它正确使用了FormData,并设置了contentType: false、processData: false等文件上传必需的参数,符合AJAX提交带文件表单的规范。

文件超过50KB无法提交的核心原因,大概率是PHP的上传相关配置限制,以下是具体排查和解决步骤:

1. 检查并修改PHP配置

默认PHP的上传限制参数可能设置得较小,导致大文件无法上传。找到你的php.ini文件,调整以下参数:

  • upload_max_filesize = 10M:设置允许上传的单个文件最大大小(可根据需求调整,比如10MB)
  • post_max_size = 12M:POST请求的总大小限制,必须大于upload_max_filesize
  • max_execution_time = 60:脚本最大执行时间(上传大文件需要更长处理时间)
  • max_input_time = 60:处理输入数据的最大时间

修改完成后,重启Web服务器(Apache/Nginx)使配置生效。

2. 查看服务器错误日志

开启错误报告后,若上传失败,可查看服务器的错误日志(比如Apache的error.log、Nginx的error.log),如果出现类似POST content-length exceeds the limit的提示,说明post_max_size配置不足,需要进一步调大。

3. 完善PHP脚本的错误处理

当前的文件上传到Telegram的函数没有错误检查,建议添加日志记录,方便排查问题:

function sendFileToTelegram($document, $caption = '') {
    global $TOKEN, $TELEGRAM_CHAT_ID;

    $url = "https://api.telegram.org/bot$TOKEN/sendDocument";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'chat_id' => $TELEGRAM_CHAT_ID,
        'document' => new CURLFile($document['tmp_name'], $document['type'], $document['name']),
        'caption' => $caption
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec($ch);
    
    // 添加错误检查与日志记录
    if(curl_errno($ch)){
        $error = curl_error($ch);
        error_log("Telegram文件上传失败: " . $error);
    }
    
    curl_close($ch);
}

4. 前端添加文件大小预验证

虽然不是问题根源,但可以在前端提前检查文件大小,给用户及时提示,避免无效提交:

$(document).ready(function() {
    $("#tg").submit(function(e) {
        e.preventDefault();
        
        const maxFileSize = 10 * 1024 * 1024; // 限制为10MB,可按需调整
        const attachmentsFile = $("#attachments")[0].files[0];
        const invoiceFile = $("#invoice")[0].files[0];
        
        // 检查附件大小
        if(attachmentsFile && attachmentsFile.size > maxFileSize){
            alert("附件大小不能超过10MB");
            return;
        }
        // 检查发票文件大小
        if(invoiceFile && invoiceFile.size > maxFileSize){
            alert("发票文件大小不能超过10MB");
            return;
        }

        // 原AJAX提交代码
        $.ajax({
            type: "POST",
            url: "process_form.php",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function(response) {
                console.log(response);
                alert("表单提交成功!");
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                alert("表单提交失败,请稍后重试");
            }
        });
    });
});

内容的提问来源于stack exchange,提问作者Victor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:43:27