wso2ballerinaballerina-http

undefined symbol 'request' error in Ballerina when trying to handle http file upload


import ballerina/http;
import ballerina/io;

// import utils/pdfUpload;

configurable int port = ?;

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? {
        stream<byte[], io:Error?> streamer = check request.getByteStream();

        check io:fileWriteBlocksFromStream("./uploads/ReceivedFile.pdf", streamer);
        check streamer.close();
        return "File Received!";
    }
}

I followed the documentation, but it seems to be outdated. I also tried a different approach as shown below.

    resource function post receiver(http:Request request) returns string|error {
        byte[] fileBytes = check request.getBodyBytes();

        check io:createDir("./files"); 
        check io:fileWriteBytes("./files/ReceivedFile.pdf", fileBytes);

        return "File Received!";
    }

Both didin't work. Seeking for some expert help!


Solution

  • In the first snippet, the name used in the reference (request) is not the same as the name of the parameter (req), resulting in the undefined symbol 'request' error.

    Once the name is fixed and the http:Caller parameter is removed (since you are directly returning the response payload from the resource rather than using the caller value to respond), it should work as expected.

        resource function post upload(http:Request req) returns string|error? {
            stream<byte[], io:Error?> streamer = check req.getByteStream();
    
            check io:fileWriteBlocksFromStream("./uploads/ReceivedFile.pdf", streamer);
            check streamer.close();
            return "File Received!";
        }
    

    If the erroneous code was from the official documentation, could you report an issue here?