html前端多文件上传

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改项目投资评审')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: zoom-css"/>
    <link rel="stylesheet" th:href="@{/css/kv-table.css}"/>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content" >
        <form class="form-horizontal m" id="form-investmentreview-edit" th:object="${investmentReview}">
            <input name="id" th:field="*{id}" type="hidden">
            <h4 class="form-header h4">项目信息</h4>
            <table class="kv-table">
                <tbody>
                <tr>
                    <td class="kv-label">项目编码:</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input id="projectCode" name="projectCode"
                                   th:field="*{projectCode}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                    <td class="kv-label">项目名称:</td>
                    <td class="kv-content">
                        <div class="form-group">
                            <input id="projectName" name="projectName"
                                   th:field="*{projectName}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                </tr>
                <tr style="display:none">
                    <td class="kv-label">项目id:</td>
                    <td class="kv-content">
                        <div class="form-group" >
                            <input id="id" name="budid"
                                   th:field="*{budid}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">项目类型:</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input  id="projectTypeName" name="projectTypeName"
                                   th:field="*{projectTypeName}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                    <td class="kv-label">所属专项资金:</td>
                    <td class="kv-content">
                        <div class="form-group">
                            <input  id="belongFund" name="belongFund"
                                   th:field="*{belongFund}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">所属支出政策:</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input  id="expendPolicy" name="expendPolicy"
                                   th:field="*{expendPolicy}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                    <td class="kv-label">支出科室:</td>
                    <td class="kv-content">
                        <div class="form-group">
                            <input  name="expendDepartment"
                                   th:field="*{expendDepartment}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">预算部门:</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input  id="budgutDepartment" name="budgutDepartment"
                                   th:field="*{budgutDepartment}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                    <td class="kv-label">预算单位:</td>
                    <td class="kv-content">
                        <div class="form-group">
                            <input  name="budgutOfficeId"
                                   th:field="*{budgutOfficeId}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">合计(万元):</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input  id="total" name="total"
                                   th:field="*{total}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                    <td class="kv-label">财政拨款(万元):</td>
                    <td class="kv-content">
                        <div class="form-group">
                            <input  id="czbkXj"name="czbkXj"
                                   th:field="*{czbkXj}"
                                   readonly="true"
                                   type="text">
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
            <h4 class="form-header h4">投资评审信息</h4>
            <table class="kv-table">
                <tbody>
                <tr>
                    <td class="kv-label">项目评审机构:</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input  id="projectReviewOrg" name="projectReviewOrg"
                                    th:field="*{projectReviewOrg}"
                                    type="text">
                        </div>
                    </td>
                    <td class="kv-label">项目评审时间:</td>
                    <td class="kv-content">
                        <div class="form-group ">
                            <div class="input-group date">
                            <input name="projectReviewTime" th:value="${#dates.format(investmentReview.projectReviewTime, 'yyyy-MM-dd')}" class="form-control time-input" placeholder="yyyy-MM-dd" type="text">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">项目评审结果:</td>
                    <td class="kv-content" >
                        <div class="form-group">
                            <input  id="projectReviewResults" name="projectReviewResults"
                                    th:field="*{projectReviewResults}"
                                    type="text">
                        </div>
                    </td>
                    <td class="kv-label">项目评审办法:</td>
                    <td class="kv-content">
                        <div class="form-group">
                            <textarea name="projectReviewMethod" class="form-control">[[*{projectReviewMethod}]]</textarea>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">项目评审依据:</td>
                    <td class="kv-content"  colspan="3">
                        <div class="form-group">
                            <textarea  id="projectReviewBasis" name="projectReviewBasis"
                                    th:field="*{projectReviewBasis}"
                                       type="text"> </textarea>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="kv-label">附件上传</td>
                    <td class="kv-content" colspan="3">
                        <div class="form-group">
                            <input  id="fileData" style="height: 35px" multiple name="fileData" type="file"/>
                            <input  id="attachmentUpload" name="attachmentUpload" th:value="*{attachmentUpload}" type="hidden">
                            <div class="attach-list" id="filelist">
                                <table th:fragment="fragment-filelist">
                                    <tr>
                                        <th>文档名称</th>
                                        <th>上传人</th>
                                        <th>上传时间</th>
                                        <th>操作</th>
                                    </tr>
                                    <tbody th:if="${list != null}">
                                    <tr th:each="item : ${list}" style=" border-bottom: 1px solid lightgray">
                                        <td >[[${item.fileName}]]</td>
                                        <td>[[${item.createBy}]]</td>
                                        <td>[[${#dates.format(item.createTime, 'yyyy-MM-dd HH:mm:ss')}]]</td>
                                        <td>
                                            <button type="button" class="btn btn-primary" th:onclick="download([[${item?.fileId}]])">下载附件</button>
                                            <button type="button" class="btn btn-danger" th:onclick="del([[${item?.fileId}]])">删除附件</button>
                                        </td>
                                    </tr>
                                    </tbody>
                                    <tbody th:if="${list == null}" >
                                    <tr>
                                        <td style="text-align: center;border: 1px solid lightblue;font-size: x-large;font-family: cursive;" colspan="4">暂无附件</td>
                                    </tr>
                                    </tbody>

                                </table>
                            </div>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </form>
    </div>
    <th:block th:include="include :: footer"/>
    <th:block th:include="include :: datetimepicker-js"/>
    <th:block th:include="include :: bootstrap-prettyfile-js"/>
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: zoom-js"/>
    <script th:inline="javascript">
        var prefix = ctx + "bac/investmentreview";
        $("#form-investmentreview-edit").validate({
            focusCleanup: true
        });

         function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $('#form-investmentreview-edit').serialize());
            }
        }
    </script>
    <!--文件上传-->
    <script th:inline="javascript">
    var thumbFile = $("#fileData");
    var thumbVal = $("#attachmentUpload").val();
    var thumbVals = [];
    if (thumbVal) {
        if (thumbVal.indexOf(',') != -1) {
            thumbVals = thumbVal.split(',');
        } else {
            thumbVals.push(thumbVal);
        }
    }
    thumbFile.fileinput({
        previewFileType: "doc",
        uploadAsync: false,
        theme: 'explorer-fas',
        uploadUrl: '/system/fileInfo/upload',
        deleteUrl: '/system/fileInfo/delete2',
        // dropZoneTitle: '点击选择文件或拖拽缩略图片到这里...',
        dropZoneEnabled: false,
        showRemove: false,
        showClose: false,
        showUpload: true, //是否显示上传按钮
        showPreview: false,//是否展前预览
        overwriteInitial: false,
        initialPreviewAsData: true,
        enctype: 'multipart/form-data'
    }).on("fileuploaded", function (event, data, previewId, index) {
        var response = data.response;
        if (response.data) {
            debugger
            $.each(response.data, function (i, val) {
                thumbVals.push(val);
            });
            $("input[name=attachmentUpload]").val(thumbVals.join(","));
            let attachmentUpload=$("input[name=attachmentUpload]").val();
            refresh(attachmentUpload);
        }
    }).on('filebatchuploadsuccess', function (event, data, previewId, index) {
        var response = data.response;
        if (response.data) {
            $.each(response.data, function (i, val) {
                thumbVals.push(val);
            });
            $("input[name=attachmentUpload]").val(thumbVals.join(","));
            let attachmentUpload=$("input[name=attachmentUpload]").val();
            refresh(attachmentUpload);
        }
    }).on('filepredelete', function (event, key, jqXHR, data) {
        if (data.ids) {
            var delFileId = data.ids;
            if (thumbVals.indexOf(delFileId) > -1) {
                thumbVals = thumbVals.filter(function (item) {
                    return item != delFileId
                });
                if (thumbVals.length > 0) {
                    var photoVal = thumbVals.join(',');
                    $("input[name=attachmentUpload]").val(photoVal);
                } else {
                    $("input[name=attachmentUpload]").val("");
                }
                let attachmentUpload=$("input[name=attachmentUpload]").val();
                refresh(attachmentUpload);
            }
        }
    });


    function refresh(attachmentUpload){
        $.ajax({
            type: "post",
            url: ctx + "system/people/getInfo",
            data: {
                "attachmentUpload": attachmentUpload,
                "fragment":'fragment-filelist'
            },
            success: function(data) {
                $("#filelist").html(data);
            }
        });
    }
    //下载附件
    function download(fileId) {
        window.open(ctx +"common/download/resource?fileId=" + fileId,"_blank");
    }
    function del(delFileId) {
        layer.confirm("您确认要删改该附件? ", {
            icon: 0,
            title: "安全提示",
            btn: ['确认'	, '取消'],
            offset: ['30%']
        }, function (index) {
            debugger
            let attachmentUpload=$("#attachmentUpload").val();
            let fiiArray=[];
            if (attachmentUpload) {
                if (attachmentUpload.indexOf(',') != -1) {
                    fiiArray = attachmentUpload.split(',');
                } else {
                    fiiArray.push(attachmentUpload);
                }
            }
            if (fiiArray.indexOf(delFileId.toString()) > -1) {
                fiiArray = fiiArray.filter(function (item) {
                    return item != delFileId
                });
                if (fiiArray.length > 0) {
                    let photoVal = fiiArray.join(',');
                    $("input[name=attachmentUpload]").val(photoVal);
                } else {
                    $("input[name=attachmentUpload]").val("");
                }
                thumbVals.push($("input[name=attachmentUpload]").val());
                let newattachmentUpload  =$("input[name=attachmentUpload]").val();
                refresh(newattachmentUpload);
            }
            layer.close(index);
        });
    }
</script>
</body>
</html>

 处理上传文件类

package com.major.web.controller.system;

import com.major.common.annotation.Log;
import com.major.common.config.Global;
import com.major.common.constant.Constants;
import com.major.common.core.controller.BaseController;
import com.major.common.core.domain.AjaxResult;
import com.major.common.core.page.TableDataInfo;
import com.major.common.enums.BusinessType;
import com.major.common.json.JSONObject;
import com.major.common.utils.StringUtils;
import com.major.common.utils.file.FileUploadUtils;
import com.major.common.utils.file.FileUtils;
import com.major.common.utils.poi.ExcelUtil;
import com.major.framework.util.ShiroUtils;
import com.major.system.domain.SysFileInfo;
import com.major.system.service.ISysFileInfoService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件Controller
 *
 * @author zhuyaosong
 * @date 2019-10-31
 */
@Controller
@RequestMapping("/system/fileInfo")
public class SysFileInfoController extends BaseController {
    private String prefix = "system/fileInfo";

    @Autowired
    private ISysFileInfoService sysFileInfoService;

    @GetMapping()
    public String fileInfo() {
        return prefix + "/fileInfo";
    }

    /**
     * 查询文件列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysFileInfo sysFileInfo) {
        startPage();
        List<SysFileInfo> list = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        return getDataTable(list);
    }

    /**
     * 导出文件列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysFileInfo sysFileInfo) {
        List<SysFileInfo> list = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        ExcelUtil<SysFileInfo> util = new ExcelUtil<SysFileInfo>(SysFileInfo.class);
        return util.exportExcel(list, "fileInfo");
    }

    /**
     * 新增文件
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存文件
     */
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, SysFileInfo sysFileInfo){
        try {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String uploadPath = FileUploadUtils.upload(filePath, file);
            sysFileInfo.setFilePath(uploadPath);
            sysFileInfo.setFileType(file.getContentType());
            sysFileInfo.setCreateTime(new Date());
            sysFileInfo.setFileName(file.getOriginalFilename());
            sysFileInfoService.insertSysFileInfo(sysFileInfo);
            return AjaxResult.success(sysFileInfo);
        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.error("上传失败");
        }
    }

    /**
     * @return com.major.common.core.domain.AjaxResult
     * @Author zhuyaosong
     * @Description fileinput控件上传文件,并保存文件信息
     * @Date 11:56 2019-10-31
     * @Param [file, fileName]
     **/
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    @ResponseBody
    public JSONObject upload(@RequestParam("fileData") MultipartFile[] files) throws IOException {
        String filePath = Global.getUploadPath();
        List<Long> list = new ArrayList<Long>();
        List<String> initialPreviewList = new ArrayList<String>();
        List<JSONObject> initialPreviewConfigList = new ArrayList<JSONObject>();
        for (MultipartFile file :files) {
            String filename = file.getOriginalFilename();
            // 创建文件信息
            SysFileInfo sysFileInfo = new SysFileInfo();
            sysFileInfo.setFileName(filename);
            // 上传并返回新文件名称
            String loacalFilePath = FileUploadUtils.upload(filePath,file);
            //设置上传文件路径
            sysFileInfo.setFilePath(loacalFilePath);
            String filetype = file.getContentType();
            sysFileInfo.setCreateBy(ShiroUtils.getSysUser().getUserName());
            sysFileInfo.setCreateTime(new Date());
            sysFileInfo.setFileType(filetype);
            //保存文件信息
            sysFileInfoService.insertSysFileInfo(sysFileInfo);
            Long fileId = sysFileInfo.getFileId();
            list.add(fileId);
            initialPreviewList.add("/system/fileInfo/download/"+fileId);
            JSONObject initialPreviewConfig =  new JSONObject();
            JSONObject extra =  new JSONObject();
            extra.put("ids",fileId);
            initialPreviewConfig.put("extra",extra);
            initialPreviewConfig.put("caption",sysFileInfo.getFileName());
            String[] strArray = filename.split("\\.");
            int suffixIndex = strArray.length -1;
            initialPreviewConfig.put("type",(filetype.indexOf("image")==-1?"other":"image"));
            initialPreviewConfig.put("filetype",strArray[suffixIndex]);
            initialPreviewConfigList.add(initialPreviewConfig);
        }
        JSONObject json = new JSONObject();
        json.put("code",0);
        json.put("data",list);
        json.put("initialPreview",initialPreviewList);
        json.put("initialPreviewConfig",initialPreviewConfigList);
//        return success("上传成功", list);
        return json;
    }

    /**
     * 修改文件
     */
    @GetMapping("/edit/{fileId}")
    public String edit(@PathVariable("fileId") Long fileId, ModelMap mmap) {
        SysFileInfo sysFileInfo = sysFileInfoService.selectSysFileInfoById(fileId);
        mmap.put("sysFileInfo", sysFileInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件
     */
    @Log(title = "文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysFileInfo sysFileInfo) {
        return toAjax(sysFileInfoService.updateSysFileInfo(sysFileInfo));
    }

    /**
     * 删除文件信息
     */
    @Log(title = "文件", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(sysFileInfoService.deleteSysFileInfoByIds(ids));
    }

    /**
     * 删除文件信息并删除文件
     */
    @Log(title = "文件", businessType = BusinessType.DELETE)
    @PostMapping("/delete2")
    @ResponseBody
    public AjaxResult delete2(String ids) {

        return toAjax(1);
    }
    /**
     * 下载文件
     */
    @GetMapping("/download/{fileId}")
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response,@PathVariable("fileId") Long fileId) throws Exception{
        // 本地资源路径
        String localPath = Global.getProfile();
        SysFileInfo sysFileInfo = sysFileInfoService.selectSysFileInfoById(fileId);
        if(sysFileInfo!=null){
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(sysFileInfo.getFilePath(), Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = sysFileInfo.getFileName();
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
    }

    /**
     * 下载压缩文件
     */
//    @RequiresPermissions("system:fileInfo:download")
    @GetMapping("/downloadFile/{fileId}")
    @ResponseBody
    public void downloadZip(HttpServletRequest request, HttpServletResponse response,@PathVariable("fileId") Long fileId) throws Exception{
        // 本地资源路径
        String localPath = Global.getUploadPath();
        SysFileInfo sysFileInfo = sysFileInfoService.selectSysFileInfoById(fileId);
        if(sysFileInfo!=null){
            // 数据库资源地址
            String downloadPath = localPath + sysFileInfo.getFilePath();
            // 下载名称
            String downloadName = sysFileInfo.getFileName();
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename="+ FileUtils.setFileDownloadHeader(request, downloadName));
            response.setContentType("application/octet-stream; charset=UTF-8");
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
    }
}

业务代码:

 @PostMapping("/getInfo")
    public String getInfo(String fragment,String attachmentUpload, ModelMap mmap)
    {
        List<SysFileInfo> list=null;
        if (!"".equals(attachmentUpload)){
            list=sysFileInfoService.selectSysFileInfoByFileIds(attachmentUpload);
        }
        mmap.put("list",list);
        return prefix + "/edit::" + fragment;
    }



 /**
     * 修改项目投资评审
     */
    @GetMapping("/edit/{infoId}")
    public String edit(@PathVariable("infoId") Long infoId, ModelMap mmap)
    {
        InvestmentReview investmentReview = investmentReviewService.selectInvestmentReviewByprojectId(infoId);
      
        //预算部门
        investmentReview.setBudgutDepartment(bacBudgetDeptService.selectBacBudgetDeptById(investmentReview.getBudgutDepartmentId()).getName());
        //支出科室
        investmentReview.setExpendDepartment(bacExpendOfficeService.selectBacExpendOfficeById(investmentReview.getExpendDepartmentId()).getName());
        //项目类型
        investmentReview.setProjectTypeName( bacProjectTypeService.selectBacProjectTypeById(investmentReview.getProjectType()).getName());
        mmap.put("investmentReview", investmentReview);
        //if (investmentReview != null){
            String files=investmentReview.getAttachmentUpload();
            if (files!=null&&!"".equals(files)){
                List<SysFileInfo> fileList = sysFileInfoService.selectSysFileInfoByFileIds(files);
                mmap.put("list",fileList);
            }
        //}
        return prefix + "/edit";
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值