Layui文件下载

Layui超实用10篇技术解决方案:https://blog.csdn.net/libusi001/article/details/100065911

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

一、内容主体区域

<div class="layui-body">
        <!-- 内容主体区域 -->
        <table class="layui-hide" id="test" lay-filter="test"></table>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <h3>文件列表</h3>
            </div>
        </script>

        <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-xs"  lay-event="download">下载1</a>
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>
</div>

二、监听行工具事件

layui.use('table', function () {
        var table = layui.table;

        //监听行工具事件
        table.on('tool(test)', 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') {
                layer.msg('功能待开发');
            }
            else if (obj.event === 'download') {
                // 获取XMLHttpRequest
                var xmlResquest = new XMLHttpRequest();
                //  发起请求
                xmlResquest.open("POST", ctxPath + "fileinfo/download", true);
                // 设置请求头类型
                xmlResquest.setRequestHeader("Content-type", "application/json");
                xmlResquest.setRequestHeader("id",data.id);
                xmlResquest.responseType = "blob";
                //  返回
                xmlResquest.onload = function(oEvent) {
                    //alert(this.status);
                    var content = xmlResquest.response;
                    // 组装a标签
                    var elink = document.createElement("a");

                    //获取文件格式,截取文件后缀
                    var fileaddr = data.fileAddress;
                    var index = fileaddr.lastIndexOf(".");
                    var length  =fileaddr.length;
                    var laterName = fileaddr.substring(index,length);
                    //拼接下载的文件名
                    var newFileName = data.fileName+laterName;
                    //设置文件下载路径
                    elink.download = newFileName;
                    elink.style.display = "none";
                    var blob = new Blob([content]);

                    //解决下载不存在文件的问题,根据blob大小判断
                    if(blob.size==0){
                        layer.msg('服务器没找到此文件,请联系管理员!');
                    }else{
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        document.body.removeChild(elink);
                    }
                };
                xmlResquest.send();
            }
        });
    });

三、后台代码

 //解决中文文件不能下载的问题
    @RequestMapping("download")
    @ResponseBody
    public void download(HttpServletResponse response, HttpServletRequest httpServletRequest) {
        String fid = httpServletRequest.getHeader("id");
        int id = Integer.parseInt(fid);
        String path = fileInfoService.getAddressById(id);
        System.out.println("download2:"+123);
        FileDownload.download2(path, response);
        log.info("文件下载");
    }

四、相关工具类

import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author libusi
 * @title: FileDownload
 * @projectName nicai
 * @date 2019/5/26  14:50
 */

public  class FileDownload {
    private static final String ENCODING = "UTF-8";
    private static final String CONTENT_DISPOSITION = "Content-Disposition";
    private static final String ATTACHMENT = "attachment;filename=";
    private static final String CONTENT_TYPE = "application/octet-stream;charset=UTF-8";
    private static final String CACHE_CONTROL = "Cache-Control";
    private static final String NO_CACHE = "no-cache";
    private static final String PRAGMA = "Pragma";
    private static final String EXPIRES = "Expires";
    private static final String APPLICATION_X_MSDOWNLOAD = "application/x-msdownload";

    public static void download(String path, HttpServletResponse response) {
        OutputStream fos = null;
        FileInputStream fis = null;
        try {
            response.setHeader(PRAGMA, NO_CACHE);
            response.setHeader(CACHE_CONTROL, NO_CACHE);
            response.setCharacterEncoding(ENCODING);
            response.setHeader(CONTENT_DISPOSITION, ATTACHMENT + URLEncoder.encode(path, ENCODING));
            response.setContentType(CONTENT_TYPE);
            response.setDateHeader(EXPIRES, 0);
            fos = response.getOutputStream();
            File file = new File(path);
            if (file.exists()) {
                fis = new FileInputStream(file);
                FileCopyUtils.copy(fis, fos);
            }
            fos.flush();
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           try {
               if(fis!=null){
                   fis.close();
               }
               if (fos!=null){
                   fos.close();
               }
           }catch (Exception e){
               e.getMessage();
           }

        }
    }

    public static void download2(String path, HttpServletResponse response) {
        OutputStream fos = null;
        FileInputStream fis = null;
        try {
            response.setHeader(PRAGMA, NO_CACHE);
            response.setHeader(CACHE_CONTROL, NO_CACHE);
            response.setCharacterEncoding(ENCODING);
            response.setHeader(CONTENT_DISPOSITION, ATTACHMENT + URLEncoder.encode(path, ENCODING));
            response.setContentType(CONTENT_TYPE);
            response.setDateHeader(EXPIRES, 0);
            fos = response.getOutputStream();
            File file = new File(path);
            if (file.exists()) {
                fis = new FileInputStream(file);
                FileCopyUtils.copy(fis, fos);
            }
            fis.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null){
                    fis.close();
                }
                if (fos!=null){
                    fos.close();
                }
            }catch (Exception e){
                e.getMessage();
            }

        }
    }
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import org.springframework.lang.Nullable;

/**
 * @author libusi
 * @title: FileDownload
 * @projectName nicai
 * @date 2019/5/26  15:50
 */

public abstract class FileCopyUtils {
    public static final int BUFFER_SIZE = 4096;

    public FileCopyUtils() {
    }

    public static int copy(File in, File out) throws IOException {
        Assert.notNull(in, "No input File specified");
        Assert.notNull(out, "No output File specified");
        return copy(Files.newInputStream(in.toPath()), Files.newOutputStream(out.toPath()));
    }

    public static void copy(byte[] in, File out) throws IOException {
        Assert.notNull(in, "No input byte array specified");
        Assert.notNull(out, "No output File specified");
        copy((InputStream)(new ByteArrayInputStream(in)), (OutputStream)Files.newOutputStream(out.toPath()));
    }

    public static byte[] copyToByteArray(File in) throws IOException {
        Assert.notNull(in, "No input File specified");
        return copyToByteArray(Files.newInputStream(in.toPath()));
    }

    public static int copy(InputStream in, OutputStream out) throws IOException {
        Assert.notNull(in, "No InputStream specified");
        Assert.notNull(out, "No OutputStream specified");

        int var2;
        try {
            var2 = StreamUtils.copy(in, out);
        } finally {
            try {
                in.close();
            } catch (IOException var12) {
                ;
            }

            try {
                out.close();
            } catch (IOException var11) {
                ;
            }

        }

        return var2;
    }

    public static void copy(byte[] in, OutputStream out) throws IOException {
        Assert.notNull(in, "No input byte array specified");
        Assert.notNull(out, "No OutputStream specified");

        try {
            out.write(in);
        } finally {
            try {
                out.close();
            } catch (IOException var8) {
                ;
            }

        }

    }

    public static byte[] copyToByteArray(@Nullable InputStream in) throws IOException {
        if (in == null) {
            return new byte[0];
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            copy((InputStream)in, (OutputStream)out);
            return out.toByteArray();
        }
    }

    public static int copy(Reader in, Writer out) throws IOException {
        Assert.notNull(in, "No Reader specified");
        Assert.notNull(out, "No Writer specified");

        try {
            int byteCount = 0;
            char[] buffer = new char[4096];

            int bytesRead;
            for(boolean var4 = true; (bytesRead = in.read(buffer)) != -1; byteCount += bytesRead) {
                out.write(buffer, 0, bytesRead);
            }

            out.flush();
            int var5 = byteCount;
            return var5;
        } finally {
            try {
                in.close();
            } catch (IOException var15) {
                ;
            }

            try {
                out.close();
            } catch (IOException var14) {
                ;
            }

        }
    }

    public static void copy(String in, Writer out) throws IOException {
        Assert.notNull(in, "No input String specified");
        Assert.notNull(out, "No Writer specified");

        try {
            out.write(in);
        } finally {
            try {
                out.close();
            } catch (IOException var8) {
                ;
            }

        }

    }

    public static String copyToString(@Nullable Reader in) throws IOException {
        if (in == null) {
            return "";
        } else {
            StringWriter out = new StringWriter();
            copy((Reader)in, (Writer)out);
            return out.toString();
        }
    }
}

五、扩展:文件点击下载

 table.on('tool(safeJarInfo)', function (obj) {
            var data = obj.data;
            if (obj.event === 'download') {
                window.location.href = data.url;
            }
        });

PS:转载请注明原博客,尊重劳动成果!

有用请点赞,养成良好习惯!

疑问、交流、鼓励请留言!

发布了267 篇原创文章 · 获赞 145 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/libusi001/article/details/100689081
今日推荐