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

处理HTTP文件上传时Ballerina报undefined symbol 'request'错误求助

Ballerina HTTP文件上传问题解决

第一个代码的错误修正

你遇到的undefined symbol 'request'错误是因为函数参数命名和代码中使用的变量名不匹配:函数定义的参数是http:Request req,但代码里调用了request.getByteStream(),变量名不一致导致未定义错误。另外还需要提前创建目标目录,避免文件写入失败。

修正后的代码:

import ballerina/http;
import ballerina/io;

configurable int port = 9090;

service / on new http:Listener(port) {
    resource function get .() returns json {
        return {message: "Server is running on port " + port.toString()};
    }

    resource function post upload(http:Caller caller, http:Request req) returns string|error? {
        // 检查并创建uploads目录
        check io:createDir("./uploads");
        // 使用正确的参数名req获取字节流
        stream<byte[], io:Error?> streamer = check req.getByteStream();
        check io:fileWriteBlocksFromStream("./uploads/ReceivedFile.pdf", streamer);
        check streamer.close();
        return "File Received!";
    }
}

第二个代码的问题与优化

如果你的场景是通过表单(multipart/form-data)上传文件,直接调用getBodyBytes()会拿到整个表单的原始数据,而非单独的文件内容。需要解析multipart表单来提取文件:

优化后的代码(支持表单文件上传):

import ballerina/http;
import ballerina/io;

configurable int port = 9090;

service / on new http:Listener(port) {
    resource function get .() returns json {
        return {message: "Server is running on port " + port.toString()};
    }

    resource function post receiver(http:Request request) returns string|error {
        // 解析multipart表单数据
        http:FormData formData = check request.getFormData();
        // 获取表单中的文件字段(假设字段名为"file")
        http:FormField? fileField = formData.get("file");
        
        if fileField is http:FormField {
            check io:createDir("./files");
            // 将文件内容写入本地
            check io:fileWriteBytes("./files/ReceivedFile.pdf", fileField.value);
            return "File Received!";
        }
        
        return error("Request does not contain a file");
    }
}

测试方式

  • 测试第一个代码(直接上传二进制文件):
    curl -X POST --data-binary "@your-local-file.pdf" http://localhost:9090/upload
    
  • 测试第二个代码(表单上传):
    curl -X POST -F "file=@your-local-file.pdf" http://localhost:9090/receiver
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:45:08