springboot+thymeleaf 文件上传

pom.xml

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

application.yml

spring:
  servlet:
    multipart:
      #上传文件总的最大值
      max-request-size: 10MB
      #上传文件的最大值
      max-file-size: 10MB

index.html 文件上传页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <p>单文件上传</p>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <p><input type="file" name="file00"></p>
        <p><span th:text="${msg}"></span></p>
        <input type="submit" value="提交">
    </form>

    <hr/>
    <p>多文件上传</p>
    <form method="post" enctype="multipart/form-data" action="/batch">
        <p>文件1:<input type="file" name="file"/></p>
        <p>文件2:<input type="file" name="file"/></p>
        <p><input type="submit" value="上传"/></p>
    </form>

</body>
</html>

hello.html 上传成功的页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <p>单文件上传</p>
    <p th:text="${msg}"></p>
    <hr>
    <p>多文件上传</p>
    <ul>
        <li th:each="msg1:${msgList}" th:text="${msg1}"></li>
    </ul>

</body>
</html>

controller:  文件上传

import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Controller
public class FileUploadController {

    //单一文件上传
    @RequestMapping("/upload")
    public String uploadFile(@RequestParam("file00") MultipartFile file, Model model){
        String msg="";
        try {
            if(file.isEmpty()){
                model.addAttribute("msg","上传失败,请选择文件!");
                return "index";
            }
            String filename = file.getOriginalFilename();
            //String filePath = request.getServletContext().getRealPath("/upload");
            String filePath = ResourceUtils.getURL("classpath:").getPath()+"static/";

            //避免文件重复覆盖
            String uuid= UUID.randomUUID().toString().replaceAll("-", "");
            //时间戳分类文件
            String time =  new SimpleDateFormat("YYYY-MM").format(new Date());

            String realPath = filePath+time+"/"+uuid+filename;
            File dest = new File(realPath);
            //检测是否存在目录,无,则创建
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();//新建文件夹 多级目录
            }

            file.transferTo(dest);//文件写入

        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("msg","文件上传成功!");
        return "hello";

    }

    //多文件上传
    @RequestMapping("/batch")
    public String uploadMoreFiles(HttpServletRequest request, Model model){
        MultipartRequest request1 = (MultipartRequest)request;
        //猜测 file为 input 类型为 file
        List<MultipartFile> fileList = request1.getFiles("file");
        List<String> msgList = new ArrayList<>();
        System.out.println(fileList.size());
        try {
            String filepath = ResourceUtils.getURL("classpath:").getPath()+"static/";
            for (int i=1;i<=fileList.size();i++){
                MultipartFile file = fileList.get(i-1);
                if (file.isEmpty()){
                    msgList.add("上传第"+i+"个文件失败");
                    model.addAttribute("msgList",msgList);
                    continue;
                }
                String filename = file.getOriginalFilename();
                //避免文件重复覆盖
                String uuid= UUID.randomUUID().toString().replaceAll("-", "");
                //时间戳分类文件
                String time =  new SimpleDateFormat("YYYY-MM").format(new Date());

                String realPath = filepath+time+"s/"+uuid+filename;
                File dest = new File(realPath);
                //System.out.println("realPath"+realPath);
                //检测是否存在目录,无,则创建
                if(!dest.getParentFile().exists()){
                    dest.getParentFile().mkdirs();//新建文件夹 多级目录
                }
                msgList.add("第"+i+"个文件,上传成功!");
                file.transferTo(dest);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("msgList",msgList);
        return "hello";
    }

}

 

测试:

文件上传文件上传2文件上传3

注:目前仅实现了文件的上传

计划补充:文件下载+上传的图片展示;

上传的图片展示:

遇到的问题:  直接使用 realPath 作为图片拼接地址  浏览器报 安全错误

notallow

使用字符串拼接,也会报错404

index = realPath.lastIndexOf("static");
upFilePaths.add("../"+realPath.substring(index));

 

 

实现富文本编辑器可以使用一些开源的JavaScript库,比如常用的有: 1. CKEditor:功能强大、可扩展性好、使用方便,支持多种浏览器和平台,但是需要付费使用高级功能。 2. TinyMCE:也是一个功能强大的富文本编辑器,开源免费,支持多种浏览器和平台,易于集成到应用中。 3. Summernote:一个基于Bootstrap的富文本编辑器,开源免费,支持多种浏览器和平台,并且具有一些独特的功能,如代码视图、图片上传等。 4. Froala Editor:一个功能强大、易于使用的富文本编辑器,支持多种浏览器和平台,但是需要付费使用高级功能。 以下是基于SpringBootThymeleaf实现使用CKEditor富文本编辑器的步骤: 1. 引入CKEditor相关的JavaScript和CSS文件,可以从官网下载或者使用CDN方式引入: ```html <!-- 引入CSS --> <link rel="stylesheet" href="https://cdn.ckeditor.com/4.16.0/standard/ckeditor.css"> <!-- 引入JS --> <script src="https://cdn.ckeditor.com/4.16.0/standard/ckeditor.js"></script> ``` 2. 在Thymeleaf模板中使用CKEditor: ```html <!-- 定义富文本编辑器容器 --> <div id="editor"></div> <!-- 初始化CKEditor --> <script> CKEDITOR.replace('editor'); </script> ``` 3. 在后端Controller中获取富文本编辑器中的内容: ```java @PostMapping("/save") public String save(@RequestParam("content") String content) { // 处理富文本编辑器中的内容 return "success"; } ``` 以上就是基于SpringBootThymeleaf实现使用CKEditor富文本编辑器的步骤,其他富文本编辑器的使用方法类似。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值