layui | 拖拽上传图片,回调显示,下载图片

layui拖拽上传:

在这里插入图片描述
这里仅做了个上传,回调测试,可以随时在多情景下引入此部分代码;另外,可扩展:

  • 上传进度条(摸索中)
  • 多图上传(可参照layui批量删除文章)
  • 文件下载(单文件下载成功,多文件下载探索中【思路:打包到zip下载】)

正文

上传

0.思路

官网操作文档:https://www.layui.com/doc/modules/upload.html
在这里插入图片描述

  1. layui上传图片,支持拖拽上传
    就是调用了layui的【modules/upload.js】
    在这里插入图片描述
  2. 回调显示图片
    在这里插入图片描述

1.准备

  • jar:
 <!--文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.2</version>
    </dependency>
  • spring配置拦截器,5M以内:
<!--文件上传spring配置-->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
    <property name="maxUploadSize" value="5242880"/>
</bean>
</beans>

  • layui样式,BootStrap,jQuery
    在这里插入图片描述

2.代码

  1. 前端:(主要是id,name对应)
    在这里插入图片描述
<%--
  Created by IntelliJ IDEA.
  User: CUNGU
  Date: 2019/8/4
  Time: 9:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName()
            + ":" + request.getServerPort() + path + "/";
%>
<html>
<link rel="stylesheet" media="screen" href="${pageContext.request.contextPath}/statics/bootstrap-dist/css/bootstrap3.min.css" >
<link rel="stylesheet" href="${pageContext.request.contextPath}/statics/layui-dist/css/layui.css" media="all">
<head>
    <title>Title</title>
</head>
<body>

<!--文件上传-->
<div class="row">
    <div class="col-md-12">
        <h1>文件上传</h1>
    </div>
</div>
<!--layui拖拽上传:https://www.layui.com/doc/modules/upload.html
https://www.cnblogs.com/yysbolg/p/9117101.html
http://www.bubuko.com/infodetail-2625227.html
-->
<div class="layui-form-item">
    <div class="layui-input-inline uploadHeadImage">
        <div class="layui-upload-drag" id="headImg">
            <i class="layui-icon"></i>
            <p>点击上传图片,或将图片拖拽到此处</p>
        </div>
    </div>
    <div class="layui-input-inline">
        <div class="layui-upload-list">
            <img class="layui-upload-img headImage" src="http://t.cn/RCzsdCq" id="demo1">
            <p id="demoText"></p>
        </div>
    </div>
    <div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="progressBar">
        <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
    </div>
     <!--button class="layui-upload-button" type="button" id="up">立即提交</button-->
</div>

<script src="${pageContext.request.contextPath}/statics/bootstrap-dist/js/jquery-3.4.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/bootstrap-dist/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/layui-dist/layui.js"></script>
<script src="${pageContext.request.contextPath}/statics/layui-dist/layui.all.js"></script>

<script src="${pageContext.request.contextPath}/statics/mystyle/js/uploadFile.js"></script>

</body>
</html>

  1. 前端js:这部分是自定义的js,获取文件并url方式提交请求
layui.use(["jquery", "upload", "form", "layer", "element"], function () {
    var $ = layui.$,
        element = layui.element,
        layer = layui.layer,
        upload = layui.upload,
        form = layui.form;
    //拖拽上传
    var uploadInst = upload.render({
        elem: '#headImg'
        , url: 'http://localhost:8080/helloworld_war_exploded/upload/headImg'
        , size: 500
        //----未成功部分---
        // ,auto:false
        // ,xhr:xhrOnProgress
        // ,bindAction: '#up'
        // ,progress:function(value){//上传进度回调 value进度值
        //     console.log(value);
        //     element.progress('progressBar', value+'%')//设置页面进度条
        // }
        //-------
        , before: function (obj) {
            //预读本地文件示例,不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo1').attr('src', result); //图片链接(base64)
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            //打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
            console.log(res.data.src);
            //window.parent.uploadHeadImage(res.data.src);
            var demoText = $('#demoText');
            demoText.html('<span style="color: #21ff3d;">上传成功!!!</span>');
        }
        , error: function () {
            //演示失败状态,并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
    element.init();
});

前端成功运行效果:
在这里插入图片描述
3. controller:(保存在项目下)

/**
     * 个人信息上传
     * @return {Result}
     */
    @RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
    @ResponseBody
    public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String prefix="";
        String dateStr="";
        String uploadDir="uploadDir";//这个文件夹是创建在:helloworld/target/helloworld/statics/uploadDir,以及helloworld/statics/uploadDir处
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                dateStr = format.format(new Date());
                String filepath = request.getServletContext().getRealPath("/statics/"+ uploadDir+"/" + dateStr + "." + prefix) ;
                filepath = filepath.replace("/", "\\");//java中路径转码
                System.out.println(filepath);
                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",map2);
        map2.put("src","../../../statics/"+uploadDir +"/"+ dateStr + "." + prefix);
        return map;
    }

后端成功运行效果:
保存格式-时间戳命名:不会命名重复导致插入失败。
在这里插入图片描述
命名优化:时间戳加上原名
在这里插入图片描述

 /**
     * 个人信息上传
     * @return {Result}
     */
    @RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
    @ResponseBody
    public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String prefix="";
        String dateStr="";
        String originalName="";
        String uploadDir="uploadDir";//这个文件夹是创建在:helloworld/target/helloworld/statics/uploadDir,以及helloworld/statics/uploadDir处
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                // 文件名:头像.jpg
                originalName = file.getOriginalFilename();
                System.out.println(originalName);
                //获取格式:jpg
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                // 时间戳
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                dateStr = format.format(new Date());
                // 文件全url:D:/myworkspace/IdeaProjects/helloworld/target/helloworld/statics/uploadDir/20190804140905.jpg
                //String filepath = request.getServletContext().getRealPath("/statics/"+ uploadDir+"/" + dateStr + "." + prefix) ;
                //D:/myworkspace/IdeaProjects/helloworld/target/helloworld/statics/uploadDir/20190804140905头像.jpg
                String filepath = request.getServletContext().getRealPath("/statics/"+ uploadDir+"/" + dateStr + originalName) ;
                filepath = filepath.replace("/", "\\");
                System.out.println(filepath);
                //保存图片
                File files=new File(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        //前端回调js中:
        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",map2);
        //map2.put("src","../../../statics/"+uploadDir +"/"+ dateStr + "." + prefix);
        map2.put("src","../../../statics/"+uploadDir +"/"+ dateStr + originalName);
        return map;
    }

调用了layui封装库,拖拽上传实现还是比较简单。


我是分界线


下载

在这里插入图片描述

0.思路

之前写过一篇文章:
SSM框架(三)文件上传与下载详解:https://blog.csdn.net/cungudafa/article/details/90319533
补充:
关于java文件【下载中文文件名乱码】问题解决方案
https://blog.csdn.net/cungudafa/article/details/90340016

里面主要讲了把文件上传记录到数据库中,是通过原生方式上传文件,这里有文件命名及下载思路。

参考博客:ssm文件上传下载比较详细的案例:https://www.cnblogs.com/zfding/p/8338429.html

1.步骤

  1. 前端
<form action="${pageContext.request.contextPath}/download" name="form3" id = "form3" method="post">
    <input type = "submit" value="普通文件下载">
</form>
  1. 后端
 @RequestMapping("/download")
    public ResponseEntity<byte[]> download(Integer fileId,HttpServletRequest request,HttpServletResponse response) {
        String filepath = request.getServletContext().getRealPath("/statics/uploadDir/");
        filepath = filepath.replace("/", "\\");
        try {
            File file = new File(filepath);
            File[] files = file.listFiles();
            String fileName = files[0].getName();//随机获取一个文件,实际中按需编写代码
            System.out.println("文件的名字:"+fileName);
            response.addHeader("content-disposition", "attachment;filename="+fileName);
            FileUtils.copyFile(files[0], response.getOutputStream());
            HttpHeaders headers = new HttpHeaders();// http协议
            String userAgent = request.getHeader("User-Agent");
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {
                fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
            }else {
                fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
            }
            headers.setContentDispositionFormData("attachment", fileName);// 默认下载文件名为原始文件名
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);// 媒体流下载

            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filepath)),
                    headers, HttpStatus.CREATED);// 二进制转换为实体类型
            return entity;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

下载成功,但是报错,遗留一个小问题:
在这里插入图片描述
在这里插入图片描述

发布了192 篇原创文章 · 获赞 321 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 终极编程指南 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览