1、pom.xml
首先需要导入两个jar包
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
2、spring-service.xml
配置文件上传解析器
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
</bean>
3、FileController.java
@Controller //注解,组件扫描加入到spring容器中
@RequestMapping("/file") //类controller的映射路径
public class FileController {
/**
* 文件上传
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public JsonResult upload(MultipartFile file) {
try {
String path="D:\\images\\2020-06-17\\";
if(!new File(path).exists()) {
new File(path).mkdirs();
}
String fileName="1.xls";
file.transferTo(new File(path+fileName));
}catch(Exception e) {
e.printStackTrace();
}
return new JsonResult(JsonResult.STATE_SUCCESS,"上传成功",null);
}
}
4、file.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>笔记管理</title>
<link rel="stylesheet" href="./layui/css/layui.css" media="all">
<style>
body{margin: 10px;}
.demo-carousel{height: 200px; line-height: 200px; text-align: center;}
</style>
</head>
<body>
<div class="layui-upload-drag" id="test10">
<i class="layui-icon"></i>
<p>点击上传,或将文件拖拽到此处</p>
</div>
</br></br>
<a href="file/download.do" >下载</a>
<script src="./layui/layui.js"></script>
<script src="./js/file.js"></script>
</body>
</html>
5、file.js
layui.use(['laypage', 'layer', 'table','jquery','upload'], function(){
var laypage = layui.laypage //分页
,layer = layui.layer //弹层
,table = layui.table //表格
,$=layui.jquery //jquery
,upload=layui.upload
//拖拽上传
upload.render({
elem: '#test10'
,url: 'file/upload.do' //改成您自己的上传接口
,accept:"file"
,done: function(res){
layer.msg(res.message);
console.log(res)
}
});
});
使用到的网址有:
MavenRepository
layui