SpringBoot+Thymeleaf图片上传

SpringBoot+Thymeleaf图片上传

首先需要添加本地图片映射 我是在启动类添加


@SpringBootApplication
@MapperScan("com.example.fuxi.Mapper")
public class FuxiApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(FuxiApplication.class, args);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        /**
         * 资源映射路径
         * addResourceHandler:访问映射路径
         * addResourceLocations:资源绝对路径
         */
        registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:E:/IDEA项目/fuxi/src/main/resources/static/img/");
    }

}

HTML主页面
<td><img th:src="@{${student.file}}" width="90" height="80"></td>图片显示

 <tr style="font-weight: bold">
           <td>编号</td>
           <td>姓名</td>
           <td>年龄</td>
           <td>性别</td>
           <td>班级</td>
           <td>年级</td>
           <td>图片</td>
           <td>操作</td>
       </tr>
       <tr th:each="student:${student}" th:id="'id'+${student.sid}">
           <td th:text="${student.sid}"></td>
           <td th:text="${student.sname}"></td>
           <td th:text="${student.sage}"></td>
           <td th:text="${student.ssex}"></td>
           <td th:text="${student.classes.cname}"></td>
           <td th:text="${student.grade.gname}"></td>
           <td><img th:src="@{${student.file}}"  width="90" height="80"></td>
           <td>
               <a th:href="@{/student/findByid(sid=${student.sid})}">修改</a>
               <a th:href="@{/student/delete(sid=${student.sid})}">删除</a>
               <a th:onclick="'javascript:del('+${student.sid}+');'">删除</a>
               <!--    <a th:href="@{/student/edit(sid=${student.sid})}">修改</a>-->
           </td>
       </tr>

添加页面
<input name="file" id="file1" type="hidden"> 这name是真正向后端数据库添加的
<input type="file" id="file">这是下面jq进行操作用的

  <tr>
           <td>
               <input name="file" id="file1"  type="hidden">
               <input type="file"  id="file">
               <p id="url"><img src="" width=200></p>
               <input type="button" id="button" value="上传" >
               <input type="button" id="t_button" value="取消上传" >
           </td>
       </tr>

    $(function () {
        $("#button").click(function () {
            var form = new FormData();
            form.append("file", document.getElementById("file").files[0]);
            $.ajax({
                url: "/student/upload",        //后台url
                data: form,
                cache: false,
                async: false,
                type: "POST",                   //类型,POST或者GET
                dataType: 'json',              //数据返回类型,可以是xml、json等
                processData: false,
                contentType: false,
                success: function (data) {      //成功,回调函数
                    if (data) {
                        var pic="/imctemp-rainy/"+data.fileName;
                        alert(pic);
                        $("#url img").attr("src",pic);
                        $("#file1").val("/imctemp-rainy/"+data.fileName)
                        // alert(JSON.stringify(data));

                    } else {
                        alert("失败");
                    }

                },
                error: function (er) {          //失败,回调函数
                    alert(JSON.stringify(data));
                }
            });
        });

        $("#t_button").click(function () {
            //这里分割字符串 /imctemp-rainy/157352875235607c10257539a5f4dcdaab233ca2832a5.jpg
            //需要用/分割字符先后获取最后一段字符串去上传到后台
            //alert($("#url img").attr("src"));
            var img = $("#url img").attr("src");
            var str = img.split("/");
            var str_img=str[str.length-1];
            //alert(str_img);
            $.post("/student/deleteImages",{filePath:str_img},function(data){
                alert(data);
                //这里我们取消上传成功之后去给换成一个暂无图片的一个图
                $("#url img").attr("src","/imctemp-rainy/11.jpg");
                $("#file1").val("/imctemp-rainy/11.jpg");
            });
        });
    })

添加图片需要的控制器

  public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
      File targetFile = new File(filePath);
      if (!targetFile.exists()) {
          targetFile.mkdirs();
      }
      FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
      out.write(file);
      out.flush();
      out.close();
  }
    //处理文件上传
    @ResponseBody //返回json数据
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public JSONObject uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        String contentType = file.getContentType();
        //System.out.print(contentType);
        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
        String filePath = "E:/IDEA项目/fuxi/src/main/resources/static/img/";
        JSONObject jo = new JSONObject();//实例化json数据

        if (file.isEmpty()) {
            jo.put("success", 0);
            jo.put("fileName", "");
        }
        try {
            uploadFile(file.getBytes(), filePath, fileName);
            jo.put("success", 1);
            jo.put("fileName", fileName);
            // jo.put("xfileName", filePath+"/"+fileName);
        } catch (Exception e) {
            // TODO: handle exception

        }


        //返回json
        return jo;

    }


    @ResponseBody //返回json数据
    @RequestMapping("deleteImages")
    public String deleteImages(HttpServletRequest request) {
        String resultInfo = null;
        String filePath = request.getParameter("filePath");
        //这里是可以在控制器分割字符的一个方法
        //int lastIndexOf = filePath.lastIndexOf("/");
        //String sb = filePath.substring(lastIndexOf+1,filePath.length());
        //由于我们只获取了图片的名称并没有获取到所有的地址,,所以我们需要去给他进行添加存放图片的地址
        File file = new File("E:/IDEA项目/fuxi/src/main/resources/static/img/"+filePath);
        if (file.exists()) {
            if (file.delete()) {
                resultInfo = "1-删除成功";
            }else {
                resultInfo = "0-删除失败";
            }
        }else {
            resultInfo = "文件不存在!";
        }
        return resultInfo;
    }

修改页面

   <tr>
               <!--      <td><img th:src="@{${student.file}}"  width="90" height="80"></td>-->
                     <th>
                         <input name="file" id="file1"  type="hidden">
                         <input type="file"  id="file">
                         <p id="url"><img th:src="@{${student.file}}"  width="90" height="80"></p>
                         <input type="button" id="button" value="上传" >
                         <input type="button" id="t_button" value="取消上传" >
                     </th>
                 </tr>

修改页面所需的jq和controller与添加的一样

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现富文本编辑器可以使用一些开源的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、付费专栏及课程。

余额充值