springboot(七)文件上传与下载

x33g5p2x  于2021-12-17 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(580)

springboot实现单文件、多文件上传与文件下载

      新建项目:springboot-file,打开pom.xml文件加入相关依赖

  1. <dependencies>
  2. <!--web-->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!--thymeleaf模板引擎-->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-test</artifactId>
  15. <scope>test</scope>
  16. </dependency>
  17. </dependencies>

 配置application.properties,内容如下:

  1. #单个数据的大小
  2. spring.servlet.multipart.max-file-size = 100Mb
  3. #总数据的大小
  4. spring.servlet.multipart.max-request-size=100Mb

 :如果不配置单个数据大小,springboot默认的上传文件的大小为1MB,大于这个值就会报错。

编写文件配置类:FileConfig.java

  1. public class FileConfig {
  2. //对应的上传目录
  3. public static final String UPLOAD_PATH = "D:/img/";
  4. //允许上传的图片格式
  5. public static final String[] UPLOAD_IMAGE_TYPES = {"jpg","ico","gif","png"};
  6. //允许上传的文件格式
  7. public static final String[] UPLOAD_FILE_TYPES ={"doc","docx","xls","xlsx","txt"};
  8. //保存文件
  9. public static final long FILE_MAX_SIZE = 3L * 1024 * 1024;
  10. }

编写控制器:FileController.java

  1. @Controller
  2. public class FileController {
  3. @GetMapping("/index")
  4. public String index() {
  5. return "index";
  6. }
  7. /**
  8. * 单文件上传
  9. * @param file
  10. * @return
  11. */
  12. @PostMapping("/upload")
  13. @ResponseBody
  14. public String fileUpload(@RequestParam("fileName") MultipartFile file) {
  15. //判断文件是否为空
  16. if (file.isEmpty()) {
  17. return "空文件";
  18. }
  19. if (file.getSize() > FileConfig.FILE_MAX_SIZE) {
  20. return "文件超过指定大小";
  21. }
  22. //获取文件名
  23. String fileName = file.getOriginalFilename();
  24. //获取文件后缀
  25. String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
  26. //文件格式判断
  27. if (!Arrays.asList(FileConfig.UPLOAD_IMAGE_TYPES).contains(type.toLowerCase())
  28. && !Arrays.asList(FileConfig.UPLOAD_FILE_TYPES).contains(type.toLowerCase())) {
  29. return "图片类型不对";
  30. }
  31. //加入当前时间重命名文件,尽量避免文件名称重复
  32. String path = FileConfig.UPLOAD_PATH + new SimpleDateFormat("yyyyMMddHHmmss").
  33. format(new Date()) + "_" + fileName;
  34. File file1 = new File(path);
  35. //判断文件是否已经存在
  36. if (file1.exists()) {
  37. return "文件已存在";
  38. }
  39. //判断文件父目录是否存在
  40. if (!file1.getParentFile().exists()) {
  41. file1.getParentFile().mkdir();
  42. }
  43. try {
  44. //保存文件
  45. file.transferTo(file1);
  46. } catch (IOException e) {
  47. return "上传文件失败";
  48. }
  49. return path;
  50. }
  51. /**
  52. * 多文件上传
  53. * @param request
  54. * @return
  55. */
  56. @PostMapping("/uploads")
  57. @ResponseBody
  58. public Map<String, String> fileUploads(HttpServletRequest request){
  59. Map<String,String> map=new HashMap<String,String>();
  60. //fileNames为页面的文件控件的name
  61. List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("fileNames");
  62. for (MultipartFile file:files) {
  63. //获取文件名
  64. String fileName = file.getOriginalFilename();
  65. if (!file.isEmpty()) {
  66. if (file.getSize() > FileConfig.FILE_MAX_SIZE) {
  67. map.put(fileName,"文件超过指定大小");
  68. continue;
  69. }
  70. //获取文件后缀
  71. String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
  72. //文件格式判断
  73. if (!Arrays.asList(FileConfig.UPLOAD_IMAGE_TYPES).contains(type.toLowerCase())
  74. && !Arrays.asList(FileConfig.UPLOAD_FILE_TYPES).contains(type.toLowerCase())) {
  75. map.put(fileName,"图片类型不对");
  76. continue;
  77. }
  78. //加入当前时间重命名文件,尽量避免文件名称重复
  79. String path = FileConfig.UPLOAD_PATH + new SimpleDateFormat("yyyyMMddHHmmss").
  80. format(new Date()) + "_" + fileName;
  81. File file1 = new File(path);
  82. //判断文件是否已经存在
  83. if (file1.exists()) {
  84. map.put(fileName,"文件已存在");
  85. continue;
  86. }
  87. //判断文件父目录是否存在
  88. if (!file1.getParentFile().exists()) {
  89. file1.getParentFile().mkdir();
  90. }
  91. try {
  92. //保存文件
  93. file.transferTo(file1);
  94. } catch (IOException e) {
  95. map.put(fileName,"上传文件失败");
  96. }
  97. } else {
  98. map.put(fileName,"空文件");
  99. }
  100. }
  101. return map;
  102. }
  103. /**
  104. * 文件下载
  105. * @param request
  106. * @param response
  107. * @return
  108. */
  109. @GetMapping("/download")
  110. @ResponseBody
  111. public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
  112. // 生成的文件名
  113. String fileName = "a.jpg";
  114. if (fileName != null) {
  115. //设置文件路径
  116. File file = new File(FileConfig.UPLOAD_PATH+fileName);
  117. //File file = new File(realPath , fileName);
  118. if (file.exists()) {
  119. // 设置强制下载不打开
  120. response.setContentType("application/force-download");
  121. // 设置文件名
  122. response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
  123. byte[] buffer = new byte[1024];
  124. FileInputStream fis = null;
  125. BufferedInputStream bis = null;
  126. try {
  127. fis = new FileInputStream(file);
  128. bis = new BufferedInputStream(fis);
  129. OutputStream os = response.getOutputStream();
  130. int i = bis.read(buffer);
  131. while (i != -1) {
  132. os.write(buffer, 0, i);
  133. i = bis.read(buffer);
  134. }
  135. return "下载成功";
  136. } catch (Exception e) {
  137. e.printStackTrace();
  138. } finally {
  139. if (bis != null) {
  140. try {
  141. bis.close();
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. if (fis != null) {
  147. try {
  148. fis.close();
  149. } catch (IOException e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. }
  154. }
  155. }
  156. return "下载失败";
  157. }
  158. }

在/resouces/templates/下编写页面文件:index.html

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>$Title$</title>
  6. </head>
  7. <body>
  8. <p>-----------------------------------单文件上传-----------------------------------</p>
  9. <form action="upload" method="post" enctype="multipart/form-data">
  10. <p>选择文件: <input type="file" name="fileName"/></p>
  11. <p><input type="submit" value="提交"/></p>
  12. </form>
  13. <p>-----------------------------------多文件上传-----------------------------------</p>
  14. <form action="uploads" method="post" enctype="multipart/form-data">
  15. <p>选择文件1: <input type="file" name="fileNames"/></p>
  16. <p>选择文件2: <input type="file" name="fileNames"/></p>
  17. <p><input type="submit" value="提交"/></p>
  18. </form>
  19. <p>-----------------------------------文件下载-----------------------------------</p>
  20. <a href="/download">文件下载</a>
  21. </body>
  22. </html>

**注:**1.html文件中要使用thymeleaf语法,得加入<html xmlns:th="http://www.thymeleaf.org">

       2. thymeleaf默认得模板配置文件位置在/resouces/templates/下,所以我们使用默认得,application.properties配置文件中就不用管啦

       3. 多文件上传中我返回一个map,如果map中有键值对数据,键代表文件名称,值代表提示的信息。

       

测试访问:ip:端口/index,文件上传下载到此结束!

最后,封装了一个文件工具类,用的上得可以瞅瞅哦!

  1. public class FileUtils {
  2. public static String fileToBase64(File file) {
  3. String base64 = null;
  4. InputStream in = null;
  5. try {
  6. in = new FileInputStream(file);
  7. byte[] bytes = new byte[(int) file.length()];
  8. in.read(bytes);
  9. base64 = Base64.getEncoder().encodeToString(bytes);
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. } finally {
  13. if (in != null) {
  14. try {
  15. in.close();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. return base64;
  22. }
  23. public static File base64ToFile(String base64) {
  24. File file = null;
  25. BufferedOutputStream bos = null;
  26. FileOutputStream fos = null;
  27. try {
  28. byte[] bytes = Base64.getDecoder().decode(base64);
  29. file = new File(formatDate() + "base64ToFile.png");
  30. fos = new FileOutputStream(file);
  31. bos = new BufferedOutputStream(fos);
  32. bos.write(bytes);
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. } finally {
  36. if (bos != null) {
  37. try {
  38. bos.close();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. if (fos != null) {
  44. try {
  45. fos.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. return file;
  52. }
  53. //删除文件
  54. public static boolean deleteFile(String fileName) {
  55. File file = new File(fileName);
  56. if (file.exists() && file.isFile()) {
  57. file.delete();
  58. return true;
  59. }
  60. return false;
  61. }
  62. //清空文件夹
  63. public static boolean deleteDir(String path) {
  64. File file = new File(path);
  65. //判断是否待删除目录是否存在
  66. if (!file.exists()) {
  67. System.err.println("The dir are not exists!");
  68. return false;
  69. }
  70. //取得当前目录下所有文件和文件夹
  71. String[] content = file.list();
  72. for (String name : content) {
  73. File temp = new File(path, name);
  74. //判断是否是目录
  75. if (temp.isDirectory()) {
  76. //递归调用,删除目录里的内容
  77. deleteDir(temp.getAbsolutePath());
  78. //删除空目录
  79. temp.delete();
  80. } else {
  81. //直接删除文件
  82. if (!temp.delete()) {
  83. System.err.println("Failed to delete " + name);
  84. }
  85. }
  86. }
  87. return true;
  88. }
  89. public static String formatDate() {
  90. return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
  91. }
  92. public static void main(String[] args) {
  93. // System.out.println(deleteFile("G:/test/test.txt"));
  94. // File file = new File("D:/img/a.jpg");
  95. // String fileToBase64 = fileToBase64(file);
  96. // System.out.println(fileToBase64);
  97. //
  98. // File file1 = base64ToFile(fileToBase64);
  99. // System.out.println(file1.getName());
  100. }
  101. }

源码地址https://gitee.com/xu0123/springboot2

相关文章