若依框架bootstrap实现文件上传:

若依框架bootstrap实现文件上传:

  1. 引入相关的js和css
<th:block th:include="include :: bootstrap-fileinput-css" />
<th:block th:include="include :: bootstrap-fileinput-js" />
  1. 引入文件标签
<input type="hidden" name="singleFile" id="singleFile1">
                            <div class="file-loading">
                                <input id="singleFile" name="file" type="file" >
                            </div>
  1. 引入js代码
 <!-- 资料上传的实现-->
       $(document).ready(function(){
            //单文件上传
            $("#singleFile").fileinput({
                uploadUrl: prefix + "/upload",
                maxFileCount: 1,
                autoReplace: true//自动替换
            }).on('fileuploaded',function(event,data,previewId,index) {
                var rsp = data.response;
                log.info("return url:" + rsp.url)
                log.info("return fileName:" + rsp.fileName)
                log.info("return newFileName:" + rsp.newFileName)
                log.info("return originalFilename: " + rsp.originalFilename)
            }).on('fileremoved',function (event, id, index){
                $("input[name='" + event.currentTarget.id +"']").val('')
            })
        });

后端代码的实现

/**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            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());
        }
    }

Logo

快速构建 Web 应用程序

更多推荐