thymeleaf,bootstrap-fileinput 多文件上传

组件遍历上传

一、前端

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"/>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-gdzcxx-edit" th:object="${bizGdzcxx}">
            <input name="gdzcxxId" th:field="*{gdzcxxId}" type="hidden">
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">资产名称:</label>
                <div class="col-sm-8">
                    <input name="zcmc" th:field="*{zcmc}" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">资产型号:</label>
                <div class="col-sm-8">
                    <input name="zcxh" th:field="*{zcxh}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">资产照片:</label>
                <div class="col-sm-8">
                    <input type="text" name="zczp" th:field="*{zczp}">
                    <div class="file-loading">
                        <input class="form-control file-upload" id="zczp" name="file" type="file" multiple>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <script th:inline="javascript">
        var prefix = ctx + "biz/gdzcxx";
        $("#form-gdzcxx-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $('#form-gdzcxx-edit').serialize());
            }
        }
        $(".file-upload").each(function (i) {
            var val = $("input[name='" + this.id + "']").val();
            var preView = val.split(',');
            $(this).fileinput({
                'uploadUrl': ctx + 'common/upload',
                initialPreviewAsData: true,
                initialPreview: preView,
                maxFileCount: 10,
                maxFileSize: 1000,
                autoReplace: true
            }).on('fileuploaded', function (event, data, previewId, index) {
                //多文件上传后,将文件名路径用","拼接起来
                if(data.response.fileName){
                    var filenames = data.response.fileName;
                    var currentFilename = $("input[name='" + event.currentTarget.id + "']").val();
                    if(currentFilename!=''){
                        filenames = currentFilename +',' +filenames;
                    }
                    $("input[name='" + event.currentTarget.id + "']").val(filenames);
                }
            }).on('fileremoved', function (event, id, index) {
                var fileIndex = index.replace('init-','');
                var currentFilename = $("input[name='" + event.currentTarget.id + "']").val();
                var fileNames = currentFilename.split(',');
                var lastFileNames = '';
                for(var i in fileNames){
                    if(i == parseInt(fileIndex)){
                        continue;
                    }
                    lastFileNames += fileNames[i]+',';
                }
                lastFileNames = lastFileNames.split(',').slice(0,-1).join(',');
                $("input[name='" + event.currentTarget.id + "']").val(lastFileNames);
            })
            $(this).fileinput('_initFileActions');
        });
    </script>
</body>
</html>

二、后端

java 复制代码
@Controller
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    

    /**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = "D:/upload";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
java 复制代码
@Component
public class ServerConfig
{
    /**
     * 获取完整的请求路径,包括:域名,端口,上下文访问路径
     * 
     * @return 服务地址
     */
    public String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
}
相关推荐
哆木7 分钟前
部署在线GBA游戏,并通过docker安装启动
游戏·html·gba
天下无贼!1 小时前
2024年最新版Vue3学习笔记
前端·vue.js·笔记·学习·vue
Jiaberrr1 小时前
JS实现树形结构数据中特定节点及其子节点显示属性设置的技巧(可用于树形节点过滤筛选)
前端·javascript·tree·树形·过滤筛选
赵啸林1 小时前
npm发布插件超级简单版
前端·npm·node.js
罔闻_spider1 小时前
爬虫----webpack
前端·爬虫·webpack
吱吱鼠叔1 小时前
MATLAB数据文件读写:1.格式化读写文件
前端·数据库·matlab
爱喝水的小鼠2 小时前
Vue3(一) Vite创建Vue3工程,选项式API与组合式API;setup的使用;Vue中的响应式ref,reactive
前端·javascript·vue.js
盏灯2 小时前
前端开发,场景题:讲一下如何实现 ✍电子签名、🎨你画我猜?
前端
WeiShuai2 小时前
vue-cli3使用DllPlugin优化webpack打包性能
前端·javascript
Wandra2 小时前
很全但是超级易懂的border-radius讲解,让你快速回忆和上手
前端