springboot+layui实现文件的上传与下载

文件上传

逻辑

  • 本项目与layui前端框架结合,实现的样式是,用户点击上传文件按钮,选择文件,选择完了之后自动上传,另外也会讲解不自动上传,绑定为监听点击某个按钮之后上传,适用于和表格内容一起提交的情况。下面我们分这两种情况:选择文件自动上传不自动上传与表格内容一起上传来进行讲解。

情况一:

前端代码

  • 第一种情况,选择文件后自动上传:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <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">
    <!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</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>
<!-- 注意:如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
<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;
        }

    }
}

情况二

  • 情况二是携带表格数据进行文件的上传,详情请移步:

文件下载

前端代码

  • 这里有个大坑!千万不要用ajax请求文件下载,因为下载也要往后台传送参数,比如要下载的文件名字等等,而如果使用ajax则需要传送json数据,后台确实能收到传送的参数,但是无法将要下载的文件比如压缩包以压缩包的形式传到前台从而出发浏览器的下载行为,只能传回文件的json格式,尽量不要使用ajax而是使用下面的方法:
<!DOCTYPE html>
<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();
            }

        }


    }
  • 5
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CtrlZ1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值