<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>Layuititle>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/layui/css/layui.css" media="all">
head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>指定允许上传的文件类型legend>
fieldset>
<div class="layui-form-item">
<button type="button" style="margin-left: 30px;" class="layui-btn" id="test3"><i class="layui-icon">i>上传文件button>
div>
<div style="width:300px;">
<div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
<div class="layui-progress-bar" lay-percent="">div>
div>
div>
<script src="/layui/layui.js" charset="utf-8">script>
<script>
layui.use(['upload', 'element', 'layer'], function(){
var $ = layui.jquery
,upload = layui.upload
,element = layui.element
,layer = layui.layer;
var form = layui.form
//指定允许上传的文件类型
upload.render({
elem: '#test3'
,url: 'fileUpload' //改成您自己的上传接口https://httpbin.org/post
,accept: 'file' //普通文件
,size: 5120 //限制文件大小,单位 KB
,exts: 'pdf' //只允许上传PDF
,auto: true //选完文件后自动上传
,before: function(obj){
element.progress('demo', '0%'); //进度条复位
}
,done: function(res){
//layer.msg('上传成功');
console.log(res.state);
}
,error: function(){
//演示失败状态,并实现重传
alert("文件上传失败");
}
//进度条
,progress: function(n, index, e){
element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
if(n == 100){
//layer.msg('上传完毕', {icon: 1});
}
}
});
});
script>
body>
html>
在上面的js代码auto: true,true是自动上传,选择完文件后会自动传送文件到后台的,url: 'fileUpload’接口。
//上传老师要发布的毕设的要求
@RequestMapping("fileUpload")
@ResponseBody
public JSONObject fileUpload(MultipartFile file){
JSONObject json = new JSONObject();
if(file.isEmpty()){
json.put("state","文件为空");
}
else json.put("state","上传成功");
System.out.println("后台接受到的上传文件名及大小:"+file.getOriginalFilename()+","+file.getSize());
fileManager filemanager=new fileManager();
String parentpath =subjectPDFParentPath +allMap.get("userId")+allMap.get("userName")+"/"+"缓冲文件区";
//先将文件缓冲区里的文件清空
if(filemanager.delFiles(parentpath))
System.out.println("文件删除成功");
else
System.out.println("文件删除失败或者不存在该路径");
//再保存上传的文件
if(filemanager.upLoadsubjectPDFFile(file.getOriginalFilename(),parentpath,file)==1)
System.out.println("文件保存成功");
else
System.out.println("文件保存失败");
return json;
}
我把对于文件的各种操作封装到了fileManeger类里,该类具体代码如下:
//处理文件上传下载的工具类
public class fileManager {
//上传文件
public int upLoadsubjectPDFFile(String fileName, String parentpath, MultipartFile uploadfile){
//String fileName = uploadfile.getOriginalFilename();
File dest = new File(parentpath + "/" + fileName);
System.out.println(parentpath + "/" + fileName);
if(!dest.getParentFile().exists()){
//判断文件父目录是否存在
dest.getParentFile().mkdirs();
}
System.out.println("指导文件名:"+fileName);
System.out.println("文件大小:"+uploadfile.getSize());
try {
uploadfile.transferTo(dest); //保存文件
return 1;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
}
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>我的毕设title>
<link rel="stylesheet" href="/layui/css/layui.css" media="all">
head>
<body>
<table class="layui-hide" id="myShowSubjects" lay-filter="user">table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit" >{
{
d.state == '已完成' ? '下载文件' : '不能下载' }}</a>
script>
<script src="/layui/layui.js">script>
<script src="/js/jquery-3.3.1.js">script>
<script th:inline="javascript">
projects=JSON.parse([[${
mySubjectStudents}]])
layui.use(['table','upload','element'], function(){
var table = layui.table;
var $ = layui.jquery
,upload = layui.upload
,element = layui.element;
//第一个实例
table.render({
elem: '#myShowSubjects'
,height: 312
, cols:
[
[ //表头
{
type:'numbers'},
{
field: 'subjname', title: '毕设题目', width:'20%',align:'center'},
{
field: 'sno', title: '学生学号', width:'20%', sort: false, align:'center'},
{
field: 'stuname', title: '学生姓名', width:'20%', sort: false, align:'center'},
{
field: 'teaname', title: '负责老师', width:'20%',align:'center'},
{
field: 'state', title: '状态', width:'20%',align:'center'},
{
fixed: 'right', title:'操作', toolbar: '#barDemo', width:75,align:'center'}
//{field: 'repertory', title: '库存', width:'25%',align:'center',sort: true},
//{field: 'teachertno',title:'老师工号',width:'0%',display:"none"},
//{type:'radio',width:'20%'}
]
],
data:projects,//[{"id":"0","name":"adsf","teachername":"asdf"}],
skin: 'line' //表格风格
, even: true
, page: true //是否显示分页
, limits: [10, 20, 30]
, limit: 10 //每页默认显示的数量
});
//监听行工具事件
table.on('tool(user)', function(obj){
var data = obj.data;
//console.log(obj)
if(obj.event === 'del'){
layer.confirm('真的删除行么', function(index){
obj.del();
layer.close(index);
});
} else if(obj.event === 'edit'){
var data = obj.data;
console.log(data)
if(data.state==='已完成'){
layer.alert("确定下载文件吗?", {
icon: 3,
skin: 'layui-layer-lan layui-layer-molv'
,end: function(){
//此处不要用ajax,使用下面的方式传参
window.location.href="/downStudentSolvedSubject?sno="+data.sno+"&subjname="+data.subjname+"&stuname="+data.stuname;
}
})
}
else{
layer.alert("毕设尚未完成,不能下载", {
icon: 3,
skin: 'layui-layer-lan layui-layer-molv',
})
}
}
});
});
script>
body>
html>
@RequestMapping("downStudentSolvedSubject")
@ResponseBody
public void downStudentSolvedSubject(@RequestParam(value="sno",defaultValue ="")String sno,
@RequestParam(value="stuname",defaultValue ="")String stuname,
@RequestParam(value="subjname",defaultValue ="")String subjname,
HttpServletResponse response){
//选择的课题json
System.out.println("下载文件的人和文件"+sno+subjname);
//将json转化为对象
//JSONObject jSONObject = JSONObject.fromObject(studentInfo);
//+"/"+allMap.get("userId")+"/"+allMap.get("mySubjName");
fileManager filemanager=new fileManager();
//首先寻找该学号对应的论文文件名
String parentpath=subjectSolvePDFParentPath+sno+"/"+subjname;
List<String> filenames=filemanager.getFileNameByPath(parentpath);
parentpath+="/";
String filename=filenames.get(0);
System.out.println(parentpath+filename);
filemanager.downFile(parentpath,filename,response);
System.out.println(stuname+"的"+subjname+"毕设完成文件下载成功");
//return map;
}
filemanager下载文件函数:
//下载文件
public void downFile(String parentpath,String filename, HttpServletResponse response) {
File file = new File(parentpath+filename);
response.setCharacterEncoding("utf-8");
//response.setHeader("Content-type", "application/zip");
String downloadFilename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setContentType("application/force-download");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//设置允许跨域的key
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
if (file.exists()) {
System.out.println("文件存在");
byte[] buffer = new byte[1024];
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
//bis.close();
//fis.close();
} catch (Exception e){
e.printStackTrace();
}
}
}