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();
    		} 
    	}
    }
    
  • 相关阅读:
    [译]WCF RIA Services中的集合(2)
    Silverlight中服务通信方式的选择(WCF、Data Service、Ria Service)
    记录来敦煌一周的情况
    Silverlight通过MVVM实现多语言实时切换(含源代码)
    [译]WCF RIA Services中的集合(1)
    Silverlight Client←→Server数据同步备忘代码
    Siverlight5新功能/改进总结
    Expression Blend 5 Preview For Silverlight5 RC已发布
    你应该知道的,那些未在Silverlight5Beta中出现的特性
    .NET数据库编程求索之路1.引子
  • 原文地址:https://www.cnblogs.com/fjf3997/p/13023533.html
Copyright © 2011-2022 走看看