博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot文件上传
阅读量:4323 次
发布时间:2019-06-06

本文共 5188 字,大约阅读时间需要 17 分钟。

我们在工作中经常会遇到文件上传的需求,本文使用SpringBoot简单实现文件上传。

首先Pom.xml

1     
2
3
org.springframework.boot
4
spring-boot-starter-web
5
6
7
org.springframework.boot
8
spring-boot-starter-test
9
test
10
11
12
13
org.springframework.boot
14
spring-boot-starter-thymeleaf
15
16

编写Controller层

1     @Controller   2     public class FileUploadController {   3        4         private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);   5        6         /**  7          * 跳转到单个文件上传  8          *  9          * @return 10          */  11         @RequestMapping(value = "/upload", method = RequestMethod.GET)  12         public ModelAndView upload() {  13             return new ModelAndView("/fileUpload");  14         }  15       16         /** 17          * 跳转到多个文件上传 18          * 19          * @return 20          */  21         @RequestMapping(value = "/upload/batch", method = RequestMethod.GET)  22         public ModelAndView batchUpload() {  23             return new ModelAndView("/multiFileUpload");  24         }  25       26         /** 27          * 文件上传具体实现方法(单文件上传) 28          * 29          * @param file 30          * @return 31          */  32         @RequestMapping(value = "/upload", method = RequestMethod.POST)  33         @ResponseBody  34         public String upload(@RequestParam("file") MultipartFile file) {  35             try {  36                 if (file.isEmpty()) {  37                     return "文件为空";  38                 }  39                 // 获取文件名  40                 String fileName = file.getOriginalFilename();  41                 logger.info("上传的文件名为:" + fileName);  42                 // 获取文件的后缀名  43                 String suffixName = fileName.substring(fileName.lastIndexOf("."));  44                 logger.info("文件的后缀名为:" + suffixName);  45       46                 // 设置文件存储路径  47                 String filePath = "E://xuchen//";  48                 String path = filePath + fileName + suffixName;  49       50                 File dest = new File(path);  51                 // 检测是否存在目录  52                 if (!dest.getParentFile().exists()) {  53                     dest.getParentFile().mkdirs();// 新建文件夹  54                 }  55                 file.transferTo(dest);  56                 return "上传成功";  57             } catch (IllegalStateException e) {  58                 e.printStackTrace();  59             } catch (IOException e) {  60                 e.printStackTrace();  61             }  62             return "上传失败";  63         }  64       65         /** 66          * 多文件上传 67          * 68          * @param request 69          * @return 70          */  71         @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)  72         @ResponseBody  73         public String batchUpload(HttpServletRequest request) {  74             List
files = ((MultipartHttpServletRequest) request).getFiles("file"); 75 MultipartFile file; 76 BufferedOutputStream stream; 77 for (int i = 0; i < files.size(); ++i) { 78 file = files.get(i); 79 if (!file.isEmpty()) { 80 try { 81 byte[] bytes = file.getBytes(); 82 stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename()))); 83 stream.write(bytes); 84 stream.close(); 85 } catch (Exception e) { 86 stream = null; 87 return "文件上传失败 " + i + " => " + e.getMessage(); 88 } 89 } else { 90 return "文件上传失败 " + i + "原因:上传文件为空!"; 91 } 92 } 93 return "文件上传成功"; 94 } 95 }

文件上传相关配置

1     @Configuration   2     public class FileUploadConfiguration {   3        4         @Bean   5         public MultipartConfigElement multipartConfigElement() {   6             MultipartConfigFactory factory = new MultipartConfigFactory();   7             // 设置文件大小限制 ,超出设置页面会抛出异常信息,   8             // 这样在文件上传的地方就需要进行异常信息的处理了;   9             factory.setMaxFileSize("2MB");  10             /// 设置总上传数据总大小  11             factory.setMaxRequestSize("5MB");  12             return factory.createMultipartConfig();  13         }  14     }

前端页面(单个上传)

1        2        3        4         
5 单个文件上传 6 7 8

文件上传示例

9

10
11

12 文件: 13

14

15 16

17
18 19

测试结果

Demo源码下载地址:

转载于:https://www.cnblogs.com/PreachChen/p/9006595.html

你可能感兴趣的文章
[ACM_模拟][ACM_数学] LA 2995 Image Is Everything [由6个视图计算立方体最大体积]
查看>>
1040 有几个PAT
查看>>
BZOJ 1412 [ZJOI2009]狼和羊的故事 | 网络流
查看>>
原型模式
查看>>
Hadoop RPC源码阅读-交互协议
查看>>
WASAPI、DirectSound/DS、WaveOut、Kernel Streaming/KS
查看>>
Perl按行分割文件
查看>>
根据现有表操作基于active record的model
查看>>
NotMapped属性特性
查看>>
Count and Say
查看>>
GridView数据导入Excel/Excel数据读入GridView
查看>>
566. Reshape the Matrix
查看>>
python数据结构与算法之搜索
查看>>
(最小点覆盖) poj 2226
查看>>
(树形DP) poj 3659
查看>>
获取类的属性名和值
查看>>
python对json的操作总结
查看>>
学习进度表第十一周
查看>>
js屏蔽回车键
查看>>
Memcached通用类(基于enyim.com Memcached Client)
查看>>