配置
#限制单个文件的最大值
spring.servlet.multipart.maxFileSize =100MB
#限制上传的多个文件的总大小
spring.servlet.multipart.max-request-size =100MB
#文件上传地址
fileUrl=http://localhost:56007/msgservice
controller层
@ApiOperation(value = "上传文件")
@ResponseBody
@RequestMapping(value="/uploadFile",method= RequestMethod.POST)
public String uploadSource(@RequestParam("file") MultipartFile file) {
return indexService.uploadSource(file);
}
service层
@Autowired
private SysConfig sysConfig;
@Override
public String uploadSource(MultipartFile file) {
try {
String pathString = null;
if(file!=null) {
//获取上传的文件名称
String filename = file.getOriginalFilename();
logger.info(filename);
//文件上传时,chrome与IE/Edge对于originalFilename处理方式不同
//chrome会获取到该文件的直接文件名称,IE/Edge会获取到文件上传时完整路径/文件名
//Check for Unix-style path
int unixSep = filename.lastIndexOf('/');
//Check for Windows-style path
int winSep = filename.lastIndexOf('\\');
//cut off at latest possible point
int pos = (winSep > unixSep ? winSep:unixSep);
if (pos != -1)
filename = filename.substring(pos + 1);
// 根路径,在 resources/static/upload
String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload/";//路径,这个在本地运行会上传到target里面,如果是打包后运行则是正常的
path = System.getProperty("user.dir")+"\\mall-xdfzx\\src\\main\\resources\\static\\img\\";//这个在本地运行也是正常的
//String filenames=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" +filename;//文件名
path = java.net.URLDecoder.decode(path, "utf-8");//解决路径包含中文的情况
// 文件后缀 例如:.png
String fileSuffix = filename.substring(filename.lastIndexOf("."));
// uuid 生成文件名
String uuid = String.valueOf(UUID.randomUUID()).replaceAll("-","");
// 新的文件名,使用uuid生成文件名
String filenames = uuid + fileSuffix;
pathString = path + filenames;//上传路径
String str = sysConfig.getFileUrl() + "/upload/" + filenames;
File files=new File(pathString);//在内存中创建File文件映射对象
//打印查看上传路径
logger.info(pathString);
if(!files.getParentFile().exists()){//判断映射文件的父文件是否真实存在
files.getParentFile().mkdirs();//创建所有父文件夹
}
file.transferTo(files);//采用file.transferTo 来保存上传的文件
resMap.put("code", 200);
resMap.put("message" , "上传成功");
resMap.put("data" ,str);
resMap.put("timestamp" , TimeHelper.getCurrentDate());
String result= JsonHelper.parserMap(resMap);
return result;
}
}catch (Exception e) {
e.printStackTrace();
return super.errorResult(e.getMessage());
}
return super.errorResult("上传失败");
}
sysConfig
@Component
public class SysConfig {
@Value("${fileUrl}")//这个在配置类文件写访问路径前缀
private String fileUrl;
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}
MyWebConfig 这个类可以自定义访问路径,比如下面的可以直接通过http://127.0.0.1:9006/img/1.png来访问
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
/***
* 自定义资源映射
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//获取文件的真实路径 mall-xdfzx代表项目工程名 需要更改
String path = System.getProperty("user.dir")+"\\mall-xdfzx\\src\\main\\resources\\static\\img\\";
path = System.getProperty("user.dir")+"\\mall-xdfzx\\img\\";//根据上传接口写的地址来对应
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
registry.addResourceHandler("/img/**").
addResourceLocations("file:"+path);
}else{//linux和mac系统 可以根据逻辑再做处理
registry.addResourceHandler("/img/**").
addResourceLocations("file:"+path);
}
super.addResourceHandlers(registry);
}
}
//这个方法可以映射到本地文件夹里面
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//"/xdfzx/img/**"是访问前缀,比如http://127.0.0.1:9001/xdfzx/img/1.png
registry.addResourceHandler("/xdfzx/img/**").addResourceLocations("file:" + "E:\\img\\");
}
前端
```java
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta HTTP-EQUIV="pragma" CONTENT="no-cache"/>
<meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"/>
<meta HTTP-EQUIV="expires" CONTENT="0"/>
<title></title>
<!-- 引入 layui -->
<script src="layui/layui.js"></script>
<link rel="stylesheet" href="layui/css/layui.css">
</head>
<body>
<div class="layui-upload">
<button class="layui-btn layui-btn-normal" id="testList" type="button">选择文件</button>
<div class="layui-upload-list">
<table class="layui-table">
<thead>
<tr><th>文件名</th>
<th>大小</th>
<th>状态</th>
<th>操作</th>
</tr></thead>
<tbody id="demoList"></tbody>
</table>
</div>
<button class="layui-btn" id="testListAction" type="button">开始上传</button>
</div>
<script>
var files=[];
//JavaScript代码区域
layui.use(['element','upload'], function(){
var $ = layui.jquery
,upload = layui.upload;
//上传
//多文件列表示例
var demoListView = $('#demoList')
,uploadListIns = upload.render({
elem: '#testList'
,url: 'http://localhost:56007/msgservice/index/uploadFile' //改成您自己的上传接口
,accept: 'file'
,exts: 'txt|rar|zip|doc|docx|pdf|xls|xlsx|jpg|png' //允许上传的文件类型
,multiple: true
,auto: false
,bindAction: '#testListAction'
,choose: function(obj){
var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
//读取本地文件
obj.preview(function(index, file, result){
var tr = $(['<tr id="upload-'+ index +'">'
,'<td>'+ file.name +'</td>'
,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
,'<td>等待上传</td>'
,'<td>'
,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
,'</td>'
,'</tr>'].join(''));
//单个重传
tr.find('.demo-reload').on('click', function(){
obj.upload(index, file);
});
//删除
tr.find('.demo-delete').on('click', function(){
delete files[index]; //删除对应的文件
tr.remove();
uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
});
demoListView.append(tr);
});
}
,done: function(res, index, upload){
if (res.code == 200){
files.push({"fileName":res.filename,"fileUrl":res.fileUrl,"fileSize":res.fileSize});//,"fileUrl":res.fileUrl
var json = JSON.stringify(files);
//将上传的文件信息加入到集合中并转换成json字符串
$("#fileJson").attr("value",json);
var fileUrl = res.fileUrl;
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
tds.eq(3).html('<span>'+fileUrl+'</span>');
tds.eq(4).html(''); //清空操作
return delete this.files[index]; //删除文件队列已经上传成功的文件
}
this.error(index, upload);
}
,error: function(index, upload){
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
}
});
});
</script>
</body>
</html>
layui文件在官网下载引入:https://layuion.com/
上传多个图片接口(待验证)
@PostMapping("/file")
@ApiOperation("图片上传,支持多个")
public CommonResult upPics(@RequestParam(value = "files") MultipartFile[] files, HttpServletRequest request) {
List<String> list = new LinkedList<>();
String path = sysPropertiesConfig.getLocalFilePath();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
//构建文件上传所要保存的"文件夹路径"--这里是相对路径,保存到项目根路径的文件夹下
log.info("-----------上传文件保存的路径【"+ files +"】-----------");
String format = sdf.format(new Date());
for (int i = 0; i < files.length; i++) {
StringBuilder imgPath = new StringBuilder();
imgPath.append("/img/").append(format);
MultipartFile file = files[i];
String fileName = file.getOriginalFilename();
//获取文件名后缀
String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
suffix = suffix.toLowerCase();
if (".jpg".equals(suffix) || ".jpeg".equals(suffix) || ".png".equals(suffix) || ".gif".equals(suffix)) {
fileName = UUID.randomUUID() + suffix;
File targetFile= new File(new File(path+format)+ File.separator +fileName);
imgPath.append(fileName);
list.add(imgPath.toString());
// File targetFile = new File(path, fileName);
//注意,判断父级路径是否存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
//保存
try {
file.transferTo(targetFile);
// file.getSize();
} catch (Exception e) {
LOGGER.error("fileName:"+fileName,e);
return CommonResult.failed("文件上传失败,请重新尝试");
}
} else {
return CommonResult.failed("图片格式有误,请上传.jpg、.png、.jpeg格式的文件");
}
}
return CommonResult.success(list);
}