zoukankan      html  css  js  c++  java
  • 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();
    		} 
    	}
    }
    
  • 相关阅读:
    数据库四种事务隔离级别
    JAVA自定义查询策略
    JAVA分页工具类
    Git常用指令
    TDH-大数据基础
    TDH-ssh免密登录
    TDH-search汇报理解
    TDH-常见运维指令
    pyecharts 0.5 visualmap 显示精度precision到小数
    14-influence 图机器学习之网络的影响力最大化
  • 原文地址:https://www.cnblogs.com/fjf3997/p/13023533.html
Copyright © 2011-2022 走看看