SpringBoot 文件上传下载

最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的java代码: 
1、开发环境: 
IDEA15+ Maven+JDK1.8 
2、新建一个maven工程: 
这里写图片描述 
3、工程框架 
这里写图片描述 
4、pom.xml文件依赖项


 
 
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >
  3. <modelVersion>4.0.0 </modelVersion>
  4. <groupId>SpringWebContent </groupId>
  5. <artifactId>SpringWebContent </artifactId>
  6. <packaging>war </packaging>
  7. <version>1.0-SNAPSHOT </version>
  8. <name>SpringWebContent Maven Webapp </name>
  9. <url>http://maven.apache.org </url>
  10. <parent>
  11. <groupId>org.springframework.boot </groupId>
  12. <artifactId>spring-boot-starter-parent </artifactId>
  13. <version>1.4.3.RELEASE </version>
  14. </parent>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot </groupId>
  18. <artifactId>spring-boot-starter-thymeleaf </artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot </groupId>
  22. <artifactId>spring-boot-devtools </artifactId>
  23. <optional>true </optional>
  24. </dependency>
  25. <dependency>
  26. <groupId>junit </groupId>
  27. <artifactId>junit </artifactId>
  28. <version>3.8.1 </version>
  29. <scope>test </scope>
  30. </dependency>
  31. </dependencies>
  32. <properties>
  33. <java.version>1.8 </java.version>
  34. </properties>
  35. <build>
  36. <finalName>SpringWebContent </finalName>
  37. <plugins>
  38. <plugin>
  39. <groupId>org.springframework.boot </groupId>
  40. <artifactId>spring-boot-maven-plugin </artifactId>
  41. </plugin>
  42. </plugins>
  43. </build>
  44. </project>
  • 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

5、Application.java


 
 
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class Application {
  5. public static void main (String[] args) {
  6. SpringApplication.run(Application.class, args);
  7. }
  8. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

6、FileController.java


 
 
  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.ui.Model;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import org.springframework.web.multipart.MultipartHttpServletRequest;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.*;
  14. import java.util.List;
  15. @Controller
  16. public class FileController {
  17. @RequestMapping( "/greeting")
  18. public String greeting (@ RequestParam (value= "name" , required= false , defaultValue= "World" ) String name, Model model) {
  19. model.addAttribute( "name", name);
  20. return "greeting";
  21. }
  22. private static final Logger logger = LoggerFactory.getLogger(FileController.class);
  23. //文件上传相关代码
  24. @RequestMapping(value = "upload")
  25. @ResponseBody
  26. public String upload (@ RequestParam ("test") MultipartFile file) {
  27. if (file.isEmpty()) {
  28. return "文件为空";
  29. }
  30. // 获取文件名
  31. String fileName = file.getOriginalFilename();
  32. logger.info( "上传的文件名为:" + fileName);
  33. // 获取文件的后缀名
  34. String suffixName = fileName.substring(fileName.lastIndexOf( "."));
  35. logger.info( "上传的后缀名为:" + suffixName);
  36. // 文件上传后的路径
  37. String filePath = "E://test//";
  38. // 解决中文问题,liunx下中文路径,图片显示问题
  39. // fileName = UUID.randomUUID() + suffixName;
  40. File dest = new File(filePath + fileName);
  41. // 检测是否存在目录
  42. if (!dest.getParentFile().exists()) {
  43. dest.getParentFile().mkdirs();
  44. }
  45. try {
  46. file.transferTo(dest);
  47. return "上传成功";
  48. } catch (IllegalStateException e) {
  49. e.printStackTrace();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. return "上传失败";
  54. }
  55. //文件下载相关代码
  56. @RequestMapping( "/download")
  57. public String downloadFile (org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
  58. String fileName = "FileUploadTests.java";
  59. if (fileName != null) {
  60. //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
  61. String realPath = request.getServletContext().getRealPath(
  62. "//WEB-INF//");
  63. File file = new File(realPath, fileName);
  64. if (file.exists()) {
  65. response.setContentType( "application/force-download"); // 设置强制下载不打开
  66. response.addHeader( "Content-Disposition",
  67. "attachment;fileName=" + fileName); // 设置文件名
  68. byte[] buffer = new byte[ 1024];
  69. FileInputStream fis = null;
  70. BufferedInputStream bis = null;
  71. try {
  72. fis = new FileInputStream(file);
  73. bis = new BufferedInputStream(fis);
  74. OutputStream os = response.getOutputStream();
  75. int i = bis.read(buffer);
  76. while (i != - 1) {
  77. os.write(buffer, 0, i);
  78. i = bis.read(buffer);
  79. }
  80. System.out.println( "success");
  81. } catch (Exception e) {
  82. e.printStackTrace();
  83. } finally {
  84. if (bis != null) {
  85. try {
  86. bis.close();
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91. if (fis != null) {
  92. try {
  93. fis.close();
  94. } catch (IOException e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. }
  99. }
  100. }
  101. return null;
  102. }
  103. //多文件上传
  104. @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
  105. @ResponseBody
  106. public String handleFileUpload (HttpServletRequest request) {
  107. List<MultipartFile> files = ((MultipartHttpServletRequest) request)
  108. .getFiles( "file");
  109. MultipartFile file = null;
  110. BufferedOutputStream stream = null;
  111. for ( int i = 0; i < files.size(); ++i) {
  112. file = files.get(i);
  113. if (!file.isEmpty()) {
  114. try {
  115. byte[] bytes = file.getBytes();
  116. stream = new BufferedOutputStream( new FileOutputStream(
  117. new File(file.getOriginalFilename())));
  118. stream.write(bytes);
  119. stream.close();
  120. } catch (Exception e) {
  121. stream = null;
  122. return "You failed to upload " + i + " => "
  123. + e.getMessage();
  124. }
  125. } else {
  126. return "You failed to upload " + i
  127. + " because the file was empty.";
  128. }
  129. }
  130. return "upload successful";
  131. }
  • 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
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134

7、index.html


 
 
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Getting Started: Serving Web Content </title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  6. </head>
  7. <body>
  8. <p>Get your greeting <a href="/greeting">here </a> </p>
  9. <form action="/upload" method="POST" enctype="multipart/form-data">
  10. 文件: <input type="file" name="test"/>
  11. <input type="submit" />
  12. </form>
  13. <a href="/download">下载test </a>
  14. <p>多文件上传 </p>
  15. <form method="POST" enctype="multipart/form-data" action="/batch/upload">
  16. <p>文件1: <input type="file" name="file" /> </p>
  17. <p>文件2: <input type="file" name="file" /> </p>
  18. <p> <input type="submit" value="上传" /> </p>
  19. </form>
  20. </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

本文代码参考Spring官网:https://spring.io/guides/gs/serving-web-content/ 
完整工程地址:http://download.csdn.net/detail/coding13/9739116

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值