SpringBoot+BootStrap多文件上传到本地
2023-09-14 08:57:06 时间
1、application.yml文件配置
1 # 文件大小 MB必须大写 2 # maxFileSize 是单个文件大小 3 # maxRequestSize是设置总上传的数据大小 4 spring: 5 servlet: 6 multipart: 7 enabled: true 8 max-file-size: 20MB 9 max-request-size: 20MB
2、application-resources.yml配置(自定义属性)
1 #文件上传路径 2 file: 3 filepath: O:/QMDownload/Hotfix2/
3、后台代码
(1)FileService.java:
1 package com.sun123.springboot.service; 2 3 import org.springframework.web.multipart.MultipartFile; 4 5 import java.util.Map; 6 7 public interface FileService { 8 9 Map<String,Object> fileUpload(MultipartFile[] file); 10 }
(2)FileServiceImpl.java:
1 package com.sun123.springboot.service.impl; 2 3 4 import com.sun123.springboot.FileUtil; 5 import com.sun123.springboot.service.FileService; 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.beans.factory.annotation.Value; 10 import org.springframework.stereotype.Service; 11 import org.springframework.web.multipart.MultipartFile; 12 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 import java.io.File; 16 import java.io.FileInputStream; 17 import java.io.PrintWriter; 18 import java.util.*; 19 20 /** 21 * @ClassName FileServiceImpl 22 * @Description TODO 23 * @Date 2019/3/22 22:19 24 * @Version 1.0 25 */ 26 @Service 27 public class FileServiceImpl implements FileService { 28 private static Logger log= LoggerFactory.getLogger(FileServiceImpl.class); 29 30 //文件上传路径 @Service包含@Component 31 @Value("${file.filepath}") 32 private String filepath; 33 34 35 Map<String, Object> resultMap = new LinkedHashMap<String, Object>(); 36 //会将上传信息存入此处,根据需求自行调整 37 List<String> fileName =new ArrayList<String>(); 38 39 //必须注入,不可以创建对象,否则配置文件引用的路径属性为null 40 @Autowired 41 FileUtil fileUtil; 42 43 @Override 44 public Map<String, Object> fileUpload(MultipartFile[] file) { 45 46 HttpServletRequest request = null; 47 HttpServletResponse response; 48 49 resultMap.put("status", 400); 50 if(file!=null&&file.length>0){ 51 //组合image名称,“;隔开” 52 // List<String> fileName =new ArrayList<String>(); 53 PrintWriter out = null; 54 //图片上传 55 56 try { 57 for (int i = 0; i < file.length; i++) { 58 if (!file[i].isEmpty()) { 59 //上传文件,随机名称,","分号隔开 60 fileName.add(fileUtil.uploadImage(request, filepath+"upload/"+ fileUtil.formateString(new Date())+"/", file[i], true)+fileUtil.getOrigName()); 61 62 } 63 } 64 //上传成功 65 if(fileName!=null&&fileName.size()>0){ 66 System.out.println("上传成功!"); 67 resultMap.put("images",fileName); 68 resultMap.put("status", 200); 69 resultMap.put("message", "上传成功!"); 70 }else { 71 resultMap.put("status", 500); 72 resultMap.put("message", "上传失败!文件格式错误!"); 73 } 74 } catch (Exception e) { 75 e.printStackTrace(); 76 resultMap.put("status", 500); 77 resultMap.put("message", "上传异常!"); 78 } 79 System.out.println("==========filename=========="+fileName); 80 81 }else { 82 resultMap.put("status", 500); 83 resultMap.put("message", "没有检测到有效文件!"); 84 } 85 return resultMap; 86 } 87 88 }
(3)FileUtil.java:
1 package com.sun123.springboot; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.stereotype.Component; 5 import org.springframework.web.multipart.MultipartFile; 6 7 import javax.servlet.http.HttpServletRequest; 8 import java.io.File; 9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 12 /** 13 * Created by wangluming on 2018/5/24. 14 */ 15 @Component 16 public class FileUtil { 17 18 // //文件上传路径 19 // @Value("${file.filepath}") 20 // private String filepath; 21 22 //文件随机名称 23 private String origName; 24 25 public String getOrigName() { 26 return origName; 27 } 28 29 public void setOrigName(String origName) { 30 this.origName = origName; 31 } 32 33 /** 34 * 35 * @param request 36 * @param path_deposit 新增目录名 支持多级不存在目录 37 * @param file 待文件 38 * @param isRandomName 是否要基于图片名称重新编排名称 39 * @return 40 */ 41 public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) { 42 43 44 //上传 45 try { 46 String[] typeImg={"gif","png","jpg","docx","doc","pdf"}; 47 48 if(file!=null){ 49 origName=file.getOriginalFilename();// 文件原名称 50 System.out.println("上传的文件原名称:"+origName); 51 // 判断文件类型 52 String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null; 53 if (type!=null) { 54 boolean booIsType=false; 55 for (int i = 0; i < typeImg.length; i++) { 56 if (typeImg[i].equals(type.toLowerCase())) { 57 booIsType=true; 58 } 59 } 60 //类型正确 61 if (booIsType) { 62 //存放图片文件的路径 63 //String path="O:\\QMDownload\\Hotfix\\"; 64 //String path=filepath; 65 //System.out.print("文件上传的路径"+path); 66 //组合名称 67 //String fileSrc = path+path_deposit; 68 String fileSrc = path_deposit; 69 //是否随机名称 70 if(isRandomName){ 71 //随机名规则:文件名+_CY+当前日期+8位随机数+文件后缀名 72 origName=origName.substring(0,origName.lastIndexOf("."))+"_CY"+formateString(new Date())+ 73 MathUtil.getRandom620(8)+origName.substring(origName.lastIndexOf(".")); 74 } 75 System.out.println("随机文件名:"+origName); 76 //判断是否存在目录 77 File targetFile=new File(fileSrc,origName); 78 if(!targetFile.exists()){ 79 targetFile.getParentFile().mkdirs();//创建目录 80 } 81 82 //上传 83 file.transferTo(targetFile); 84 //完整路径 85 System.out.println("完整路径:"+targetFile.getAbsolutePath()); 86 return fileSrc; 87 } 88 } 89 } 90 return null; 91 }catch (Exception e) { 92 e.printStackTrace(); 93 return null; 94 } 95 } 96 97 /** 98 * 格式化日期并去掉”-“ 99 * @param date 100 * @return 101 */ 102 public String formateString(Date date){ 103 SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd"); 104 String list[] = dateFormater.format(date).split("-"); 105 String result = ""; 106 for (int i=0;i<list.length;i++) { 107 result += list[i]; 108 } 109 return result; 110 } 111 }
(4)MathUtil.java:
1 package com.sun123.springboot; 2 3 import java.security.MessageDigest; 4 import java.util.Random; 5 6 public class MathUtil { 7 /** 8 * 获取随机的数值。 9 * @param length 长度 10 * @return 11 */ 12 public static String getRandom620(Integer length){ 13 String result = ""; 14 Random rand = new Random(); 15 int n = 20; 16 if(null != length && length > 0){ 17 n = length; 18 } 19 boolean[] bool = new boolean[n]; 20 int randInt = 0; 21 for(int i = 0; i < length ; i++) { 22 do { 23 randInt = rand.nextInt(n); 24 25 }while(bool[randInt]); 26 27 bool[randInt] = true; 28 result += randInt; 29 } 30 return result; 31 } 32 /** 33 * MD5 加密 34 * @param str 35 * @return 36 * @throws Exception 37 */ 38 public static String getMD5(String str) { 39 MessageDigest messageDigest = null; 40 try { 41 messageDigest = MessageDigest.getInstance("MD5"); 42 messageDigest.reset(); 43 messageDigest.update(str.getBytes("UTF-8")); 44 } catch (Exception e) { 45 //LoggerUtils.fmtError(MathUtil.class,e, "MD5转换异常!message:%s", e.getMessage()); 46 } 47 48 byte[] byteArray = messageDigest.digest(); 49 StringBuffer md5StrBuff = new StringBuffer(); 50 for (int i = 0; i < byteArray.length; i++) { 51 if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) 52 md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); 53 else 54 md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); 55 } 56 return md5StrBuff.toString(); 57 } 58 }
(5)FileController.java:
1 package com.sun123.springboot.controller; 2 3 import com.sun123.springboot.service.FileService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RequestParam; 8 import org.springframework.web.bind.annotation.ResponseBody; 9 import org.springframework.web.multipart.MultipartFile; 10 11 import java.util.Map; 12 13 /** 14 * @ClassName FileController 15 * @Description TODO 16 * @Date 2019/3/22 22:21 17 * @Version 1.0 18 */ 19 @Controller 20 @RequestMapping(value = "/upload") 21 public class FileController { 22 23 @Autowired 24 private FileService fileService; 25 26 @RequestMapping(value = "/UpLoadImage") 27 @ResponseBody 28 public Map<String,Object> fileUpload(@RequestParam("file") MultipartFile[] file) throws Exception { 29 Map<String, Object> fileUpload = fileService.fileUpload(file); 30 return fileUpload; 31 } 32 }
4、前台代码(bootstrap)
1 <div class="container" th:fragment="fileupload"> 2 <input id="uploadfile" type="file" class="file" multiple="multiple" name="file"/> 3 4 </div> 5 6 7 <script> 8 $("#uploadfile").fileinput({ 9 10 language: 'zh', //设置语言 11 12 //uploadUrl: "http://127.0.0.1/testDemo/fileupload/upload.do", //上传的地址 13 uploadUrl: "/upload/UpLoadImage", //上传的地址 14 15 allowedFileExtensions: ['jpg', 'gif', 'png', 'docx', 'zip', 'txt'], //接收的文件后缀 16 17 //uploadExtraData:{"id": 1, "fileName":'123.mp3'}, 18 showClose: false,//是否显示关闭按钮 19 20 uploadAsync: true, //默认异步上传 21 22 showUpload: true, //是否显示上传按钮 23 24 //showBrowse: true, //是否显示浏览按钮 25 26 showRemove: true, //显示移除按钮 27 28 showPreview: true, //是否显示预览 29 30 showCaption: false, //是否显示标题 31 32 browseClass: "btn btn-primary", //按钮样式 33 34 dropZoneEnabled: true, //是否显示拖拽区域 35 36 //previewFileType: ['docx'], //预览文件类型 37 //minImageWidth: 50, //图片的最小宽度 38 39 //minImageHeight: 50,//图片的最小高度 40 41 //maxImageWidth: 1000,//图片的最大宽度 42 43 //maxImageHeight: 1000,//图片的最大高度 44 45 maxFileSize:0,//单位为kb,如果为0表示不限制文件大小 46 47 //minFileCount: 0, 48 49 maxFileCount: 10, //表示允许同时上传的最大文件个数 50 51 enctype: 'multipart/form-data', 52 53 validateInitialCount: true, 54 55 previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>", 56 57 msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", 58 59 }).on("fileuploaded", function (event, data, previewId, index) { 60 61 62 }); 63 </script>
相关文章
- 宝塔部署 springboot 项目遇到的 一些bug处理方案
- SpringBoot入门之基于XML的Mybatis
- Springboot集成MapperFactory(ma.glasnost.orika.MapperFactory)类属性复制
- SpringBoot ( 七 ) :springboot + mybatis 多数据源最简解决方案
- SpringBoot+SpringCloud
- Springboot扩展点之InitializingBean
- SpringBoot中@Mapper和@Repository注解的区别
- 【SpringBoot5】SpringBoot中使用Cors开启跨域
- springboot定时任务,SERVICE层无法注入问题详细解决
- 【springboot系列】自定义一个拦截器,附源码
- 实践丨SpringBoot整合Mybatis-Plus项目存在Mapper时报错
- SpringBoot 异常回滚 事务的使用___Springboot @Transactional 事务不回滚
- Springboot如何实现自动输出word文档功能?实例代码解析(word文档答题试卷)
- Springboot整合Spring的.xm配置文件
- 在SpringBoot项目中添加logback的MDC
- SpringBoot实例②springboot+jdbcTemplate小例子实现增删查改
- SpringBoot整合swagger报错java.lang.NoClassDefFoundError: javax/validation/constraints/Min
- 【最全最详细】Jenkins+Docker 一键自动化部署 SpringBoot 项目
- Spring、SpringBoot常见面试题与答案
- SpringBoot ——Spring Boot日志配置
- 进化,从Spring到SpringBoot
- IntelliJ IDEA 创建 SpringBoot 项目 Maven 打包 jar