Upload file using Spring mvc and MockMVC

若如初见. 提交于 2019-12-05 02:09:39
public void testAddContacts() throws Exception{
            File f = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
            System.out.println(f.isFile()+"  "+f.getName()+f.exists());
            FileInputStream fi1 = new FileInputStream(f);
            FileInputStream fi2 = new FileInputStream(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulips.jpg"));
            MockMultipartFile fstmp = new MockMultipartFile("upload", f.getName(), "multipart/form-data",fi1);
            MockMultipartFile secmp = new MockMultipartFile("upload", "Tulips.jpg","multipart/form-data",fi2); 
            MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
            mockMvc.perform(MockMvcRequestBuilders.fileUpload("/AddContacts")                
                    .file(fstmp)
                    .file(secmp)
                    .param("name","abc").param("email","abc@gmail.com").param("phone", "1234567890"))               
                    .andExpect(status().isOk());
    }

The method MockMvcRequestBuilders.fileUpload is deprecated

fileUpload @Deprecated public static
MockMultipartHttpServletRequestBuilder fileUpload(java.net.URI uri)
Deprecated. in favor of multipart(URI) Create a
MockMultipartHttpServletRequestBuilder for a multipart request.
Parameters: uri - the URL Since:
4.0.3

To instead of fileUpload(), use this way.

  MockMultipartFile mockMultipartFile = new MockMultipartFile("user-file",fileName,
          "text/plain", "test data".getBytes());

  MockHttpServletRequestBuilder builder =
          MockMvcRequestBuilders.multipart("/upload")
                                .file(mockMultipartFile);

Or

MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());

mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
                .file("file", jsonFile.getBytes())
                .characterEncoding("UTF-8"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!