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

Godot 4.1.4向API发送图片时Unicode解析错误求助

问题与解决方案

问题背景

用Godot 4.1.4开发包含故事(文本+图片)的应用,通过Node.js编写的REST API将数据存入MySQL,API在Postman中可正常接收multipart/form-data格式数据(包含user_id、title、pages、images字段),但在Godot中发送图片时出现Unicode解析错误:Unicode parsing error, some characters were replaced with � (U+FFFD): Invalid UTF-8 leading byte (89)。当前使用FileAccess.get_as_text()将图片转为文本拼入请求,尝试过base64编码未解决问题。

错误原因

图片属于二进制数据,get_as_text()会强制将二进制字节按UTF-8文本解析,而图片字节并非合法UTF-8编码,导致解析失败并产生乱码。同时手动拼接multipart/form-data字符串的方式无法正确处理二进制内容,因为字符串本质是文本类型,无法保留二进制字节的原始值。

解决方案

使用Godot内置的MultipartForm类构建请求,该类专门用于处理multipart/form-data类型的表单,能自动处理边界、编码和二进制数据,无需手动拼接内容。

修改后的代码

func upload_story():
    var url = "http://localhost:3000/add-story"
    # 准备HTTPRequest节点
    var http_request = HTTPRequest.new()
    add_child(http_request)
    http_request.request_completed.connect(self._on_request_completed)

    # 读取图片二进制数据
    var file = FileAccess.open("res://Assets/images/Story Images/Story1/student.png", FileAccess.READ)
    var image_buffer = file.get_buffer(file.get_length())
    file.close()

    # 构建MultipartForm表单
    var form = MultipartForm.new()
    # 添加文本字段
    form.add_part("user_id", "1".to_utf8())
    form.add_part("title", "MyStoryExample".to_utf8())
    # 将pages数组转为JSON字符串后添加
    var pages_json = JSON.stringify([
        {"page_number": 1, "text_content": "It was a sunny day at the park."},
        {"page_number": 2, "text_content": "Children were playing, and birds chirped."}
    ])
    form.add_part("pages", pages_json.to_utf8())
    # 添加图片文件
    form.add_file("images", image_buffer, "image.png", "image/png")

    # 发送请求
    var headers = ["Content-Type: multipart/form-data; boundary=" + form.get_boundary()]
    http_request.request(url, headers, HTTPClient.METHOD_POST, form.get_data())

func _on_request_completed(result, response_code, headers, body):
    if response_code == 201:
        print("请求成功")
        print(String(body))
    else:
        print("请求失败,响应码: ", response_code)

关键改动说明

  • 二进制数据读取:用get_buffer()替代get_as_text(),直接获取图片的原始二进制字节,避免UTF-8解析错误。
  • MultipartForm使用:
    • 文本字段通过add_part()添加,需转为UTF-8字节数组(to_utf8())。
    • 数组类型的pages先转为JSON字符串,再转为UTF-8字节添加,确保后端能正确解析JSON格式。
    • 图片文件用add_file()方法,自动处理文件名、Content-Type和二进制数据,无需手动拼接边界和头部。
  • 请求发送:通过form.get_data()获取完整的请求体,form.get_boundary()获取自动生成的边界值,确保请求格式正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:14:54