Springboot 上傳與下載
阿新 • • 發佈:2019-01-27
TDD設計模式
一、Test類
@RunWith(SpringRunner.class) @SpringBootTest 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); } }
二、controller類
@RestController @RequestMapping("/file") //上傳 public class FileController { private String folder = "/main/java/com/imooc/web/controller"; @PostMapping public FileInfo upload(MultipartFile file) throws Exception { InputStream inputStream = file.getInputStream(); // 可以直接獲取輸入流 byte[] bytes = new byte[0]; bytes = new byte[inputStream.available()];//根據輸入流的大小 建立位元組陣列 inputStream.read(bytes); String str = new String(bytes,"utf-8"); //處理中文亂碼 System.out.println(str); 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()); //返回的本地檔案的絕對路徑 } @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();) { //JDK1.7的新語法 自動關閉流 response.setContentType("application/x-download"); response.addHeader("Content-Disposition", "attachment;filename=test.txt"); IOUtils.copy(inputStream, outputStream); outputStream.flush(); } } }