layui+SpringBoot上传文件,分页列表,下载、搜索一站式

能够帮到你们的话,就给我留个言,给我一点信心记录更多有用的东西

成品页面

layui+SpringBoot上传文件,分页列表,下载、搜索一站式_第1张图片

pom.xml

<!--Fastdfs 分布式文件系统FDFS-->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.1-RELEASE</version>
</dependency>
<!--excel工具-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>

html页面

<!--附件上传-->
<div class="layui-tab-item">
    <div class="layui-row">
        <form class="layui-form layui-col-md12 x-so">
            <div class="layui-input-inline">
                <input type="text" value="" id="fileName" placeholder="附件名称" class="layui-input">
            </div>
            <a class="layui-btn search_btn"><i class="layui-icon">&#xe615;</i></a>
            <button type="button" class="layui-btn layui-btn-sm" id="fileUpload"><i class="layui-icon"></i>上传文件
            </button>
        </form>
    </div>
    <table class="layui-table" id="hjTable" lay-filter="hjFilter"></table>
    <div class="page" id="pageDiv"></div>
</div>
<!-- 工具栏模板 -->
<div class="tool_template" type="text/html" id="toolBar">
   <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="download">下载</a>
</div>

js

var busId = parent.pkId;
       fileTableIns = table.render({
           //设置表头
           cols: [[
               {type: 'numbers', title: '序号', fixed: 'left'},
               {
                   field: 'fileName',
                   title: '附件名称',
                   align: 'center',
                   minWidth: 180,
                   templet: '
{{d.fileName==""?"-":d.fileName}}
'
}, { field: 'fileSize', title: '附件大小', minWidth: 180, align: 'center', templet: '
{{(d.fileSize / 1024).toFixed(1)}}kb
'
}, {field: 'opt', title: '操作', fixed: 'right', width: 260, align: 'center', toolbar: '#toolBar'} ]], url: "back/hj/queryListPage", contentType: 'application/json',//加此参数传参方式为 json method: 'POST', where: { //设定异步数据接口的额外参数,任意设 condition: { "busId": busId, "fileName": $("#fileName").val() } }, request: { pageName: 'current', //页码的参数名称,默认:page limitName: 'size' //每页数据量的参数名,默认:limit }, response: { statusCode: 200, //成功的状态码,默认:0 msgName: 'message' //状态信息的字段名称,默认:msg }, elem: '#hjTable', page: { elem: 'pageDiv', limit: 10, } }); //监听行单击事件(双击事件为:rowDouble) table.on('row(hjFilter)', function (obj) { //标注选中样式 // obj.tr.addClass('layui-bg-green').siblings().removeClass('layui-bg-green'); obj.tr.addClass('layui-bg-light-green').siblings().removeClass('layui-bg-light-green'); // console.log(obj.tr) //得到当前行元素对象 // console.log(obj.data) //得到当前行数据 //obj.del(); //删除当前行 //obj.update(fields) //修改当前行数据 }); //监听工具条 table.on('tool(hjFilter)', function (obj) { //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值" var data = obj.data; var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值) if (layEvent === 'download') { //下载 layer.confirm('您确定要下载 ' + data.fileName + ' 吗?', {icon: 3, title: '下载提示'}, function () { index = top.layer.msg('文件加载中,请稍候', {icon: 16, time: false, shade: 0.8}); window.location.href = requestLink + "back/hj/download?id=" + data.id; layer.closeAll('dialog'); top.layer.close(index); }); } }); //查询 $(".search_btn").click(function () { fileTableIns.reload({ where: { //设定异步数据接口的额外参数,任意设 condition: { "busId": busId, "fileName": $("#fileName").val() } }, page: { curr: 1 //重新从第 1 页开始 } }); }); //文件上传 upload.render({ elem: '#fileUpload', size: 1024 * 50, url: 'back/hj/uploading?busId=' + busId, accept: 'file',//普通文件 exts: 'docx|docm|dotx|dotm|xlsx|xlsm|xltx|xltm|xlsb|xlam|pptx|pptm|ppsx|ppsx|potx|potm|ppam|pdf|PNG|JPEG|JPG|GIF', before: function (obj) { //obj参数包含的信息,跟 choose回调完全一致,可参见上文。 index = top.layer.msg('文件上传中,请稍候', {icon: 16, time: false, shade: 0.8}); }, progress: function (n, elem) {//文件上传进度的回调 var percent = n + '%' //获取进度百分比 // element.progress('demo', percent); //可配合 layui 进度条元素使用 //以下系 layui 2.5.6 新增 // console.log(elem); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。 console.log(percent); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。 }, done: function (res) { top.layer.close(index); if (res.code == "200") { layer.msg('上传成功', {icon: 1}); fileTableIns.reload({page: {curr: 1}}); } else { layer.msg(res.message, {icon: 2}); } }, error: function (index, upload) { top.layer.close(index); layer.msg("系统异常", {icon: 2}); } });

后台控制器

package com.soa.ump.server.controllerBack;

import com.soa.common.core.constant.Constant;
import com.soa.common.core.constant.SysConstant;
import com.soa.common.core.model.PageModel;
import com.soa.common.web.model.ResultModel;
import com.soa.common.web.util.ResultUtil;
import com.soa.common.web.util.ReturnUtilServer;
import com.soa.ump.server.message.CommonFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.*;
import com.soa.common.web.BaseController;
import com.soa.bus.model.HjAccessory;
import com.soa.bus.rpc.api.IHjAccessoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.Map;
/**
* 

* 文件表前端控制器 *

* * @author Xing * @since 2020-06-15 */
@RestController @RequestMapping("/back/hj") @Api(value = "HjController", description = "附件上传下载管理Api") public class HjController extends BaseController { @Autowired private CommonFileUtil commonFileUtil; private static final String PREFIXED = "http://192.168.1.1/";//上传IP地址 @ApiOperation(value = "上传附件", notes = "上传附件") @ApiImplicitParams({ @ApiImplicitParam(name = "busId", value = "业务Id", dataType = "String", required = true, paramType = "query"), }) @PostMapping(value = "/uploading") public Map<String, Object> saveTfAttachment(@RequestParam("file") MultipartFile attachmentFile, Long busId) { try { long size = attachmentFile.getSize(); if (size > (1024 * 1024 * 50)) { return returnUtil.returnMess(Constant.OPERATION_FAILURE, "无法上传,单文件最大可上传50MB"); } String attachmentOriginalName = attachmentFile.getOriginalFilename();//文件源名 System.out.println("文件大小:" + attachmentFile.getSize()); System.out.println("文件源名:" + attachmentOriginalName); System.out.println("type:" + busType); //FastDFS上传 String filePath = this.commonFileUtil.uploadFile(attachmentFile); //新增附件信息 执行新增方法 Hj accessory = this.service.add(new HjAccessory(busId, attachmentOriginalName, filePath, PREFIXED, size, super.getCurrentUserId())); if (accessory != null) { return returnUtil.returnMess(accessory.getId()); } else { return returnUtil.returnMess(Constant.OPERATION_FAILURE); } } catch (Exception e) { e.printStackTrace(); return returnUtil.returnMess(Constant.DATA_ERROR); } } /** * 附件下载 * * @param id 文件ID * @param request * @param response * @return void * @author Xing * @date 2020-05-10 */ @GetMapping("/download") public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) { HjAccessory entity = service.selectById(id); try { String headerKey = "Content-Disposition"; String filename = new String(entity.getFileName().getBytes(), "ISO-8859-1"); String headerValue = String.format("attachment; filename=" + filename); /*String fullPath = entity.getFilePath() + entity.getFileNName();//得到文件路径 File downloadFile = new File(fullPath); ServletContext context = request.getServletContext(); String mimeType = context.getMimeType(fullPath); if (mimeType == null) { mimeType = "application/octet-stream"; } response.setContentType(mimeType); response.setContentLength((int) downloadFile.length());*/ response.setHeader(headerKey, headerValue); byte[] download = this.commonFileUtil.download(entity.getFilePath()); InputStream myStream = new ByteArrayInputStream(download); IOUtils.copy(myStream, response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } }

工具类

package com.soa.ump.server.message;

import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.proto.storage.DownloadFileWriter;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.soa.common.tools.StringUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Set;

/**
 * FastFDS文件上传工具类
 *
 * @author Xing
 * @date 2020-06-01
 */
@Component
public class CommonFileUtil {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    //    private static final String PREFIXED = "http://47.96.226.188";

    /**
     * MultipartFile类型的文件上传ַ
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 普通的文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        StorePath path = fastFileStorageClient.uploadFile(inputStream, file.length(),
                FilenameUtils.getExtension(file.getName()), null);
        return getResAccessUrl(path);
    }

    /**
     * 带输入流形式的文件上传
     *
     * @param is
     * @param size
     * @param fileName
     * @return
     */
    public String uploadFileStream(InputStream is, long size, String fileName) {
        StorePath path = fastFileStorageClient.uploadFile(is, size, fileName, null);
        return getResAccessUrl(path);
    }

    /**
     * 将一段文本文件写到fastdfs的服务器上
     *
     * @param content
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath path = fastFileStorageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(path);
    }

    /**
     * 返回文件上传成功后的地址名称ַ
     *
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        return storePath.getGroup() + "/" + storePath.getPath();
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public void deleteFile(String filePath) {
        if (StringUtil.isEmpty(filePath)) {
            return;
        }
        try {
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            StorePath storePath = new StorePath(group, path);
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            System.out.println("error" + e.getMessage());
        }
    }

    /**
     * 文件下载
     *
     * @param filePath
     * @return byte[]
     * @author Xing
     * @date 2020-06-01
     */
    public byte[] download(String filePath) {
        String group = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = this.fastFileStorageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }

}

你可能感兴趣的:(layui+boot,LayUI,Spring,Springboot,java,intellij,idea)