简体   繁体   中英

Multiple file upload with rest-assured

I have a post api call which allows me to upload multiple images within form-data parameter named "file" In postman, i can send multiple file in form-data having key "file" and values as multiple file

I want to simulate the same call with rest-assured java client. I could upload single file with rest-assured but unable to upload multiple files.

Following is the rest-assured code for single file upload:

 File sheetFile = new File(sheetPath.get(0)); response = RestAssured. given(). headers(headers). formParameter("studentDetail", "{"+ "\\"userId\\" : "+PropFileHandler.readProperty("psUserId")+ ",\\"institutionId\\" : "+PropFileHandler.readProperty("institution_id")+ ",\\"externalUserId\\" : "+PropFileHandler.readProperty("user_id")+ ",\\"tokenId\\" : \\"12000\\""+ ",\\"imagePathStatus\\" : \\"\\""+ "}"). formParameter("clientType", getData("ps_bulk_upload_image.clientType")). multiPart("file", sheetFile). #here i want to upload multile files when(). post(relativePath). then(). statusCode(200). body(matchesJsonSchema(new File(test.cngActions.getJsonSchemaDirectoryPath()+ getData("ps_bulk_upload_image.schemaPath")))). extract().response();

Any help would be appreciated.

Just call multiPart multiple times.

See here: https://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/

Relevant code:

given().
  multiPart("file1", new File("/home/johan/some_large_file.bin")).
  multiPart("file2", new File("/home/johan/some_other_large_file.bin")).
  multiPart("file3", "file_name.bin", inputStream).
  formParam("name", "value").
expect().
  body("fileUploadResult", is("OK")).
when().
  post("/advancedFileUpload");

You only has to call multipart method with the same controlName all the times that you need.

RestAssuredMockMvc
    .given()
        .log().all()
        .headers(httpHeaders)
        .contentType(MediaType.MULTIPART_FORM_DATA.toString())
        .multiPart("content", file1)
        .multiPart("content", file2)

With that you send the following request

Multiparts:     ------------
            Content-Disposition: form-data; name = content; filename = test1.txt
            Content-Type: application/octet-stream

            C:\Users\mgagomez\AppData\Local\Temp\junit7193983138466861544\test1.txt
            ------------
            Content-Disposition: form-data; name = content; filename = test2.txt
            Content-Type: application/octet-stream

            C:\Users\mgagomez\AppData\Local\Temp\junit7193983138466861544\test2.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM