I am sending the file as a part of the multipart request, but my API is not detecting its presence

26 Views Asked by At

I have a program that creates fake users to test my API and database, which creates a user and sends the data as a multipart request because it contains a 'file' (represented by a bytearray). The code that builds and executes the request use Apache HttpClient is below.

val req = HttpPost("http://localhost:8080/api/createuser")
        req.entity = MultipartEntityBuilder
            .create()
            .addTextBody("key", key)
            .addTextBody("username", user.username)
            .addTextBody("password", "1234")
            .addTextBody("data", user.encode())
            .addBinaryBody("picture", ByteArray(10) { 0 })
            .build()
        client.execute(req) { println(if(it.code == 200) "success" else "failure") }

However, the API endpoint fails saying that the required part 'picture' is not found. Multipart is enabled on the API, and all the other parts are present. Here is the RequestMapping for the endpoint:

    fun createUser(
        @RequestPart key: String,
        @RequestPart username: String,
        @RequestPart password: String,
        @RequestPart data: String,
        @RequestPart picture: MultipartFile
    ) {
        require(key == masterKey)
        println("File: ${picture.bytes}")
        val u = User()
        with(u) {
            this.username = username
            this.password = password
            this.userData = data
        }
        userRepository.save(u)
    }

I have looked at a println of the request, and it looks to be a valid multipart request. I have also upped the max-file-size and max-request-size properties to 15MB, way above the 10 byte test. Why is only the file not being received by the api?

1

There are 1 best solutions below

0
RandomLonelyDev On

To solve the problem, use the overload for the addBinaryBody() method that includes contentType and fileName. ex

.addBinaryBody("picture", ByteArray(10) { 0 }, ContentType.APPLICATION_OCTET_STREAM, "pic")