REST-Assured、SpringBoot 文件上传

通常我们在向服务器传输大容量的数据时(译者注:比如文件)会使用multipart表单数据技术。rest-assured提供了一种multiPart方法来辨别这究竟是文件、二进制序列、输入流还是上传的文本。表单中上传一个文件可以这样

(官方案例):
given().
        multiPart(new File("/path/to/file")).
when().
        post("/upload"); 

自己写的SpringBoot controller如下:
  @PostMapping("/file/upload")
    public String upload(@RequestParam Map paramMap, @RequestParam("file") MultipartFile file1) throws IOException {
        String url = paramMap.get("url");
        Response response = given().multiPart(CMD.MultipartFile2File(file1)).params(CMD.getParams2(paramMap)).post(url);
        System.err.println("实际返回结果::" + response.asString());
        return response.asString();
    }


MultipartFile2File方法如下:
 public static File MultipartFile2File(MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名,防止生成的临时文件重复
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        File upload = File.createTempFile(uuid, prefix);
        // MultipartFile to File
        file.transferTo(upload);
        return upload;
    }

前端:

效果如下:


image.png
接口返回(上传成功):

{
code: "1",
msg: "操作成功",
data: "0a147efcaf774461a399e82393ce77e9",
success: true
}

Maven依赖如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.1.RELEASE
         
    

    com.wan
    MyAutoTest
    1.0-SNAPSHOT


    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            mysql
            mysql-connector-java
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.alibaba
            fastjson
            1.2.47
        

        
            org.projectlombok
            lombok
        
        
            io.rest-assured
            json-schema-validator
            3.0.1
        
        
            io.rest-assured
            spring-mock-mvc
            3.0.1
        
        
            com.jayway.restassured
            rest-assured
            2.9.0
        

        
            org.testng
            testng
            6.10
        

        
        
            com.mchange
            mchange-commons-java
            0.2.11
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
        
        
            
                lib
                BOOT-INF/lib/
                
                    **/*.jar
                
            
        
    

你可能感兴趣的:(REST-Assured、SpringBoot 文件上传)