Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力于在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。
Spring Boot特點
1. 創建獨立的Spring應用程序
2. 嵌入的Tomcat,無需部署WAR文件
3. 簡化Maven配置
4. 自動配置Spring
5. 提供生產就緒型功能,如指標,健康檢查和外部配置
6. 絕對沒有代碼生成和對XML沒有要求配置[
springboot 實現文件上傳下載實例代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
@Controller public class FileUploadCtrl { @Value ( "${file.upload.dir}" ) private String path; /** * 實現文件上傳 * */ @RequestMapping (value = "/fileUpload" , method = RequestMethod.POST) @ResponseBody public Map<String,Object> fileUpload( @RequestParam ( "fileName" ) MultipartFile file){ Map<String,Object> map = new HashMap<String, Object>(); int no = 0 ; String msg = "上傳失敗!" ; if (!file.isEmpty()){ String fileName = file.getOriginalFilename(); File dest = new File(path + "/" + fileName); if (!dest.getParentFile().exists()){ //判斷文件父目錄是否存在 dest.getParentFile().mkdir(); } try { file.transferTo(dest); //保存文件 no = 1 ; msg = "上傳成功!" ; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } map.put( "no" ,no); map.put( "msg" , msg); return map; } @RequestMapping ( value = "/fileDownload" , method = RequestMethod.GET ) public ResponseEntity<?> getGwFileContent( @RequestParam String fileName, @RequestParam int flag) { HttpHeaders headers = new HttpHeaders(); headers.add( "Cache-Control" , "no-cache, no-store, must-revalidate" ); String filepath = path+ "/" +fileName;; InputStream is = null ; try { headers.add( "Content-Disposition" , String.format( "attachment; filename=\"%s\"" , new String(fileName.getBytes( "GBK" ), "ISO8859-1" ))); if (flag== 0 ){ //表示獲取縮略圖 File file = new File(filepath); filepath = path+ "/xx" +fileName; File xxFile = new File(filepath); if (!xxFile.exists()){ //不存在就生成縮略圖 Thumbnails.of(file).scale( 0 .25f).toFile(xxFile); } } is = new FileInputStream( new File(filepath)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } headers.add( "Pragma" , "no-cache" ); headers.add( "Expires" , "0" ); return ResponseEntity .ok() .headers(headers) .contentType(MediaType.parseMediaType( "application/octet-stream" )) .body( new InputStreamResource(is)); } } |
總結
以上所述是小編給大家介紹的springboot 中文件上傳下載實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/yshyee/p/7839101.html