• resstFul服务文件上传下载


    resstFul服务文件上传下载

    上传

    1. 在测试类中使用MocekMvc伪造上传文件请求
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = DemoApplication.class)
    public class UserControllerTest {
        @Autowired
    	private WebApplicationContext wac;
    	private MockMvc mockMvc;
    	@Before
    	public void setup() {
    		mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    	}
    	@Test
    	public void whenUploadSuccess() throws Exception {
    		String result = mockMvc.perform(fileUpload("/file")
    		        // 第一个参数为文件名,第二个参数为上传的原始名字,第四个参数为文件内容
    				.file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello upload".getBytes("UTF-8"))))
    				.andExpect(status().isOk())
    				.andReturn().getResponse().getContentAsString();
    		System.out.println(result);
    	}
    
    1. 编写上传文件Controller层类
    @RestController
    @RequestMapping("/file")
    public class FileController {
        private String folder = "F:\doucuments\idea\spring-security\demo\src\main\resources";
    	@PostMapping
    	public FileInfo upload(MultipartFile file) throws Exception {
    		System.out.println(file.getName());
    		System.out.println(file.getOriginalFilename());
    		System.out.println(file.getSize());
    		File localFile = new File(folder, new Date().getTime() + ".txt");
    		file.transferTo(localFile);
    		return new FileInfo(localFile.getAbsolutePath());
    	}
    }
    

    下载

    controller层编写方法

    @RestController
    @RequestMapping("/file")
    public class FileController {
    	private String folder = "F:\doucuments\idea\spring-security\demo\src\main\resources";
    	@GetMapping("/{id}")
    	public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
    		try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
    				OutputStream outputStream = response.getOutputStream();) {
    			response.setContentType("application/x-download");
    			response.addHeader("Content-Disposition", "attachment;filename=test.txt");
    			IOUtils.copy(inputStream, outputStream);
    			outputStream.flush();
    		} 
    	}
    }
    
  • 相关阅读:
    Charles的基本功能使用
    模拟器的代理功能
    LoadRunner参数包含逗号
    MySQL 与 [charlist]% 通配符
    MySQL 删除重复项并保留其中一个
    Selenium grid 分布式测试搭建(二)
    Selenium grid 分布式测试搭建(一)
    chromedriver与chrome版本映射表 与chromedriver 下载地址
    Selenium 打开 Chrome 链接框只有 Data;
    Xpath 小结
  • 原文地址:https://www.cnblogs.com/fjf3997/p/13023560.html
Copyright © 2020-2023  润新知