1、application.yml文件配置

 #  文件大小 MB必须大写
# maxFileSize 是单个文件大小
# maxRequestSize是设置总上传的数据大小
spring:
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB

2、application-resources.yml配置(自定义属性)

 #文件上传路径
file:
filepath: O:/QMDownload/Hotfix2/

3、后台代码

(1)FileService.java:

 package com.sun123.springboot.service;

 import org.springframework.web.multipart.MultipartFile;

 import java.util.Map;

 public interface FileService {

     Map<String,Object> fileUpload(MultipartFile[] file);
}

(2)FileServiceImpl.java:

 package com.sun123.springboot.service.impl;

 import com.sun123.springboot.FileUtil;
import com.sun123.springboot.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.*; /**
* @ClassName FileServiceImpl
* @Description TODO
* @Date 2019/3/22 22:19
* @Version 1.0
*/
@Service
public class FileServiceImpl implements FileService {
private static Logger log= LoggerFactory.getLogger(FileServiceImpl.class); //文件上传路径 @Service包含@Component
@Value("${file.filepath}")
private String filepath;   
Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
  //会将上传信息存入此处,根据需求自行调整
List<String> fileName =new ArrayList<String>(); //必须注入,不可以创建对象,否则配置文件引用的路径属性为null
@Autowired
FileUtil fileUtil; @Override
public Map<String, Object> fileUpload(MultipartFile[] file) { HttpServletRequest request = null;
HttpServletResponse response; resultMap.put("status", 400);
if(file!=null&&file.length>0){
//组合image名称,“;隔开”
// List<String> fileName =new ArrayList<String>();
PrintWriter out = null;
//图片上传 try {
for (int i = 0; i < file.length; i++) {
if (!file[i].isEmpty()) {
//上传文件,随机名称,","分号隔开
fileName.add(fileUtil.uploadImage(request, filepath+"upload/"+ fileUtil.formateString(new Date())+"/", file[i], true)+fileUtil.getOrigName()); }
}
//上传成功
if(fileName!=null&&fileName.size()>0){
System.out.println("上传成功!");
resultMap.put("images",fileName);
resultMap.put("status", 200);
resultMap.put("message", "上传成功!");
}else {
resultMap.put("status", 500);
resultMap.put("message", "上传失败!文件格式错误!");
}
} catch (Exception e) {
e.printStackTrace();
resultMap.put("status", 500);
resultMap.put("message", "上传异常!");
}
System.out.println("==========filename=========="+fileName); }else {
resultMap.put("status", 500);
resultMap.put("message", "没有检测到有效文件!");
}
return resultMap;
} }

(3)FileUtil.java:

 package com.sun123.springboot;

 import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date; /**
* Created by wangluming on 2018/5/24.
*/
@Component
public class FileUtil { // //文件上传路径
// @Value("${file.filepath}")
// private String filepath; //文件随机名称
private String origName; public String getOrigName() {
return origName;
} public void setOrigName(String origName) {
this.origName = origName;
} /**
*
* @param request
* @param path_deposit 新增目录名 支持多级不存在目录
* @param file 待文件
* @param isRandomName 是否要基于图片名称重新编排名称
* @return
*/
public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) { //上传
try {
String[] typeImg={"gif","png","jpg","docx","doc","pdf"}; if(file!=null){
origName=file.getOriginalFilename();// 文件原名称
System.out.println("上传的文件原名称:"+origName);
// 判断文件类型
String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
if (type!=null) {
boolean booIsType=false;
for (int i = 0; i < typeImg.length; i++) {
if (typeImg[i].equals(type.toLowerCase())) {
booIsType=true;
}
}
//类型正确
if (booIsType) {
//存放图片文件的路径
//String path="O:\\QMDownload\\Hotfix\\";
//String path=filepath;
//System.out.print("文件上传的路径"+path);
//组合名称
//String fileSrc = path+path_deposit;
String fileSrc = path_deposit;
//是否随机名称
if(isRandomName){
//随机名规则:文件名+_CY+当前日期+8位随机数+文件后缀名
origName=origName.substring(0,origName.lastIndexOf("."))+"_CY"+formateString(new Date())+
MathUtil.getRandom620(8)+origName.substring(origName.lastIndexOf("."));
}
System.out.println("随机文件名:"+origName);
//判断是否存在目录
File targetFile=new File(fileSrc,origName);
if(!targetFile.exists()){
targetFile.getParentFile().mkdirs();//创建目录
} //上传
file.transferTo(targetFile);
//完整路径
System.out.println("完整路径:"+targetFile.getAbsolutePath());
return fileSrc;
}
}
}
return null;
}catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 格式化日期并去掉”-“
* @param date
* @return
*/
public String formateString(Date date){
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
String list[] = dateFormater.format(date).split("-");
String result = "";
for (int i=0;i<list.length;i++) {
result += list[i];
}
return result;
}
}

(4)MathUtil.java:

 package com.sun123.springboot;

 import java.security.MessageDigest;
import java.util.Random; public class MathUtil {
/**
* 获取随机的数值。
* @param length 长度
* @return
*/
public static String getRandom620(Integer length){
String result = "";
Random rand = new Random();
int n = 20;
if(null != length && length > 0){
n = length;
}
boolean[] bool = new boolean[n];
int randInt = 0;
for(int i = 0; i < length ; i++) {
do {
randInt = rand.nextInt(n); }while(bool[randInt]); bool[randInt] = true;
result += randInt;
}
return result;
}
/**
* MD5 加密
* @param str
* @return
* @throws Exception
*/
public static String getMD5(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (Exception e) {
//LoggerUtils.fmtError(MathUtil.class,e, "MD5转换异常!message:%s", e.getMessage());
} byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString();
}
}

(5)FileController.java:

 package com.sun123.springboot.controller;

 import com.sun123.springboot.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import java.util.Map; /**
* @ClassName FileController
* @Description TODO
* @Date 2019/3/22 22:21
* @Version 1.0
*/
@Controller
@RequestMapping(value = "/upload")
public class FileController { @Autowired
private FileService fileService; @RequestMapping(value = "/UpLoadImage")
@ResponseBody
public Map<String,Object> fileUpload(@RequestParam("file") MultipartFile[] file) throws Exception {
Map<String, Object> fileUpload = fileService.fileUpload(file);
return fileUpload;
}
}

4、前台代码(bootstrap)

 <div class="container" th:fragment="fileupload">
<input id="uploadfile" type="file" class="file" multiple="multiple" name="file"/> </div> <script>
$("#uploadfile").fileinput({ language: 'zh', //设置语言 //uploadUrl: "http://127.0.0.1/testDemo/fileupload/upload.do", //上传的地址
uploadUrl: "/upload/UpLoadImage", //上传的地址 allowedFileExtensions: ['jpg', 'gif', 'png', 'docx', 'zip', 'txt'], //接收的文件后缀 //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
showClose: false,//是否显示关闭按钮 uploadAsync: true, //默认异步上传 showUpload: true, //是否显示上传按钮 //showBrowse: true, //是否显示浏览按钮 showRemove: true, //显示移除按钮 showPreview: true, //是否显示预览 showCaption: false, //是否显示标题 browseClass: "btn btn-primary", //按钮样式 dropZoneEnabled: true, //是否显示拖拽区域 //previewFileType: ['docx'], //预览文件类型
//minImageWidth: 50, //图片的最小宽度 //minImageHeight: 50,//图片的最小高度 //maxImageWidth: 1000,//图片的最大宽度 //maxImageHeight: 1000,//图片的最大高度 maxFileSize:0,//单位为kb,如果为0表示不限制文件大小 //minFileCount: 0, maxFileCount: 10, //表示允许同时上传的最大文件个数 enctype: 'multipart/form-data', validateInitialCount: true, previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>", msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", }).on("fileuploaded", function (event, data, previewId, index) { });
</script>

SpringBoot+BootStrap多文件上传到本地的更多相关文章

  1. laravel中的文件上传到本地+七牛云上传

    首先在filesystems.php 配置好上传的文件的目录起名为upload 在Storage/目录下面 目录下面的app/upload 如果没有这个文件会自动创建 这里的名字upload名字是跟控 ...

  2. SpringBoot项目实现文件上传和邮件发送

    前言 本篇文章主要介绍的是SpringBoot项目实现文件上传和邮件发送的功能. SpringBoot 文件上传 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码. 开发准备 环境要 ...

  3. Springboot如何启用文件上传功能

    网上的文章在写 "springboot文件上传" 时,都让你加上模版引擎,我只想说,我用不上,加模版引擎,你是觉得我脑子坏了,还是觉得我拿不动刀了. springboot如何启用文 ...

  4. springboot+vue实现文件上传

    https://blog.csdn.net/mqingo/article/details/84869841 技术: 后端:springboot 前端框架:vue 数据库:mysql pom.xml: ...

  5. Springboot(九).多文件上传下载文件(并将url存入数据库表中)

    一.   文件上传 这里我们使用request.getSession().getServletContext().getRealPath("/static")的方式来设置文件的存储 ...

  6. springboot升级导致文件上传自动配置/tmp目录问题解决

    1,..\web\src\main\resources\spring\web-men-applicationContext.xml 保留原有的bean配置 <bean id="mult ...

  7. bootstrap fileinput 文件上传

    最近因为项目需要研究了下bootstrap fileinput的使用,来记录下这几天的使用心得吧. 前台html页面的代码 <form role="form" id=&quo ...

  8. SpringBoot之KindEditor文件上传

    后端核心代码如下: package com.blog.springboot.controller; import java.io.BufferedOutputStream; import java.i ...

  9. SpringBoot: 6.文件上传(转)

    1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta c ...

随机推荐

  1. ps -ef | grep Linux进程查看命令

    我们常常会想查看Linux的一些进程,很自然地用到了: ps -ef | grep xxx ps: process show 展示进程 参数:1. e 显示所有程序. 2. f  显示UID,PPIP ...

  2. Elastic Stack之Logstash进阶

    Elastic Stack之Logstash进阶 作者:尹正杰  版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.使用GeoLite2和logstash 过滤插件的geoip案例 1>. ...

  3. java io系列03之 ByteArrayOutputStream的简介,源码分析和示例(包括OutputStream)

    前面学习ByteArrayInputStream,了解了“输入流”.接下来,我们学习与ByteArrayInputStream相对应的输出流,即ByteArrayOutputStream.本章,我们会 ...

  4. "Error 0162 - Setup data integrity check failure" after updating BIOS via Thinkvantage

    Start the computer and start pressing F1 and get into set up. In setup press F9 for default settings ...

  5. Linux记录-HDFS副本机制

    1. 副本策略 NameNode具有RackAware机架感知功能,这个可以配置. 若client为DataNode节点,那存储block时,规则为:副本1,同client的节点上:副本2,不同机架节 ...

  6. VirtualBox下安装Ubuntu Server 16.04

    安装环境: Windows:确保磁盘空间足够,一般需要8个G左右. 所需文件: 首先在Ubuntu的官网上下载.iso的镜像文件,链接是:http://www.ubuntu.org.cn/server ...

  7. NIO SocketChannel 【链接】

    Java NIO系列教程(一) Java NIO 概述 Java NIO系列教程(六) Selector Java NIO系列教程(二) Channel Java NIO系列教程(三) Buffer ...

  8. SpringMVC的概念和图解

    1.概念 Spring MVC起步:慕课网视频 SpringMVC架构浅析:参考 Spring详解(一)------概述 Spring架构简单描述 2.图片

  9. HDU - 4027 Can you answer these queries?(线段树区间修改)

    https://cn.vjudge.net/problem/HDU-4027 题意 给一个有初始值的数组,存在两种操作,T=0时将[L,R]的值求平方根,T=1时查询[L,R]的和. 分析 显然不符合 ...

  10. mysql修改表结构语句

    mysql alter 用法,修改表,字段等信息   一: 修改表信息 1.修改表名 alter table test_a rename to sys_app; 2.修改表注释 alter table ...