Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a multipart request with RestAssured?

I have @Controller with method with signature like this:

@PostMapping
@ResponseBody
public ResponseEntity<Result> uploadFileAndReturnJson(@RequestParam("file") MultipartFile file) {}

I want to construct multipart request without physically creating any file. I tried doing it like this:

private MultiPartSpecification getMultiPart() {
    return new MultiPartSpecBuilder("111,222")
            .mimeType(MimeTypeUtils.MULTIPART_FORM_DATA.toString())
            .controlName("file")
            .fileName("file")
            .build();
}

Response response = RestAssured.given(this.spec)
            .auth().basic("admin", "admin")
            .multiPart(getMultiPart())
            .when().post(URL);

Unfortunately I received response:

Required request part 'file' is not present

I tried looking at RestAssured unit tests and it seems I'm doing it correctly. If I try to pass byte[] or InputStream instead of String, an exception is thrown:

Cannot retry request with a non-repeatable request entity.

Thanks for help.

like image 897
Łukasz Chorąży Avatar asked Dec 13 '16 15:12

Łukasz Chorąży


People also ask

How do you send a multipart file in Rest assured?

If we want to send JSON we need to set the content-type as "application/json". But "application/json" should not allowing the multipart file to send on the request. So If we want to send some JSON data along with multipart file, Convert the JSON key, values as MAP and send it with . formParams, send multipart file in .

How do I upload a multipart form data?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.

How does a multipart request work?

Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).


1 Answers

Your code looks fine and it should work with byte[]. You can use MultiPartSpecBuilder(byte[] content) like below.

private MultiPartSpecification getMultiPart() {
         return new MultiPartSpecBuilder("Test-Content-In-File".getBytes()).
                fileName("book.txt").
                controlName("file").
                mimeType("text/plain").
                build();
   }

The details for error you are getting with byte[] is available at https://github.com/rest-assured/rest-assured/issues/507. According to this you should try with preemptive basic auth like below.

.auth().preemptive.basic("admin", "admin")
like image 88
abaghel Avatar answered Sep 21 '22 12:09

abaghel