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

Lua编写Discord Webhook上传图片失效问题求助

Discord Webhook图片上传问题修复

问题描述

用Lua编写的Discord Webhook发送消息正常,但上传的图片无法在Discord服务器正常显示:点击或下载图片跳转至无效链接;原PNG格式图片在Discord中被识别为JPG格式,经两个月多次修改仍未解决。

问题根源

代码错误地将图片数据包装成base64 Data URI格式放入multipart表单中,但Discord Webhook的multipart/form-data上传接口要求直接传递原始二进制文件内容,不需要额外的Data URI前缀。这种错误格式导致Discord无法正确解析文件内容,进而生成无效的CDN链接,并错误识别文件格式。

修复后的代码

function sendDiscordWebhook(webhookUrl, message, imageFilePath)
    local boundary = "----------------------------" .. os.time()

    local headers = {
        ["Content-Type"] = "multipart/form-data; boundary=" .. boundary
    }

    local body = {}
    table.insert(body, "--" .. boundary)
    table.insert(body, 'Content-Disposition: form-data; name="content"\r\n\r\n' .. message)

    if imageFilePath then
        local file = io.open(imageFilePath, "rb")
        if file then
            local imageFileData = file:read("*all")
            file:close()
            -- 处理文件名:如果是当前目录的文件,直接用文件名,否则取路径最后部分
            local fileName = imageFilePath:match("^.+[\\/](.+)$") or imageFilePath
            local fileExtension = fileName:match("%.([^%.]+)$")
            local contentType = "image/" .. fileExtension

            table.insert(body, "--" .. boundary)
            table.insert(body, 'Content-Disposition: form-data; name="file[0]"; filename="' .. fileName .. '"')
            table.insert(body, 'Content-Type: ' .. contentType)
            table.insert(body, "Content-Transfer-Encoding: binary") -- 明确编码方式
            table.insert(body, "")
            table.insert(body, imageFileData) -- 直接放入原始二进制数据
        end
    end

    table.insert(body, "--" .. boundary .. "--")
    local requestBody = table.concat(body, "\r\n")

    PerformHttpRequest(webhookUrl, function(err, text, headers)
        print("TEXT:" .. text)
        print("ERROR:" .. err)
        print("HEADERS:" .. (json and json.encode(headers) or "json module not available"))
    end, 'POST', requestBody, headers)
end

sendDiscordWebhook("https://discord.com/api/webhooks/MYWEBHOOK/MYWEBHOOK", "Test", "image.png")

关键修复点

  • 移除了不必要的base64_encode函数及Data URI格式包装,直接传递原始二进制文件数据
  • 修复了文件名获取逻辑,处理当前目录下文件的情况
  • 添加了Content-Transfer-Encoding: binary头,明确告知服务器文件编码方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:53:21