簡體   English   中英

如何在空手道中使用 multipart 上傳多個文件

[英]How do I upload multiple files with multipart in Karate

我想使用 multipart 在一個請求中上傳多個圖像文件。 我已經查看了空手道示例,但是多文件上傳不能滿足我的需要(/multiple endpoint here - https://github.com/intuit/karate/blob/master/karate-demo/src/main/java /com/intuit/karate/demo/controller/UploadController.java )。 我的服務方法 (Spring REST) 簽名需要一個 MultipartFile[] 數組,以便我可以接受任意數量的文件。 這是我的場景:

Scenario: Upload multiple files
    * def json = {}
    * set json.files[0] = { read: 'file1.jpg', filename: 'file1.jpg', contentType: 'image/jpeg' }
    * set json.files[1] = { read: 'file2.jpg', filename: 'file2.jpg', contentType: 'image/jpeg' }
    Given path '/rest' 
    And multipart files json
    When method post
    Then status 200

這是 Spring Web 服務方法(只是嘗試立即接收文件,因此該方法不會做太多事情):

@PostMapping("/rest")
public String handleFileUpload(@RequestParam("file") MultipartFile[] file) {
   System.out.println("Len: " + file.length);
   for(MultipartFile currentFile : file) {
      System.out.println("In here: " + currentFile.getOriginalFilename());
   }
   return file[0].getOriginalFilename();
}

當我運行它時,我收到一個空手道錯誤:'multipart file value should be json'

如果我改變場景來做到這一點:

    Scenario: Upload multiple files
        * def json = {}
        * set json.files = { read: 'file1.jpg', filename: 'file1.jpg', contentType: 'image/jpeg' }, { read: 'file2.jpg', filename: 'file2.jpg', contentType: 'image/jpeg' }
        Given path '/rest' 
        And multipart files json
        When method post
        Then status 200

然后測試執行正常,但只有一個文件最終出現在 MultipartFile 數組 'files'(服務方法參數)中。

使用空手道將多個文件上傳到上述 Web 服務方法的正確方法是什么?

編輯:添加客戶端代碼(如下)並更新上面的 Spring 方法。

這是一個簡單的 HTML 表單,它將向上面的 Spring 方法提交多個文件:

<form method="POST" enctype="multipart/form-data" action="/rest">
    <table>
        <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
        <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
        <tr><td></td><td><input type="submit" value="Upload" /></td></tr>
    </table>
</form>

提交后,我在服務方法中得到 2 個文件。

似乎它確實有效,您只需要在特征文件中兩次發送相同的參數

我的服務:

public ResponseEntity<StreamingResponseBody> mergePdfs(@RequestPart @Validated
            List<FileMetaData> filesMetadata, @RequestPart @Validated List<MultipartFile> files)

哇,以前從未見過這個,很可能空手道不支持它。 我還想知道這是否符合 HTTP 規范 - 據我所知 - 每個文件都必須具有唯一的字段名稱。 您是否有 Apache HTTP 客戶端的相應客戶端代碼,這會有所幫助。

編輯:另請參閱下面Esteban Lopez 的回答: https : //stackoverflow.com/a/59833358/143475

您最好的選擇可能是提交功能請求並貢獻代碼以加快速度。 請注意,這是 2 年來第一次有人報告此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM