文件上传+SpringMVC+富文本编辑器

1、基本思路

在富文本中,选择图片后,直接使用ajax完成图片的上传,上传成功之后,我们在页面上获取图片的路径。将路劲信息和富文本的信息,再统一提交。

2、前提准备

在SpringMVC配置文件中定义一个bean 类型为CommonsMultipartResolver

在SpringMVC中专门封装了一个类CommonsMultipartResolver来处理文件上传,所以需要在 SpringMVC的配置件中加入一个bean;配置bean的代码如下:

<!--文件上传-->
<!--加入一个bean用来处理文件上传,这里采用的是commons-fileupload:commons-fileupload:1.4-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

</bean>

3、具体步骤

步骤一:导入所需Jar文件

<!-- 文件上传 commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
<!-- 文件上传 commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

步骤二:使用tinymce富文本编辑器

<!--layui-tinymce富文本编辑器-->
<div class="layui-card-body">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
        <legend>文章内容</legend>
    </fieldset>
    <textarea id="edit" cols="30" rows="10" name="article_content"></textarea>
    <div class="layui-btn-group" style="margin-top: 10px">
        <button class="layui-btn" lay-submit lay-filter="form-fabu">发布</button>
    </div>
</div>
<!--Layui富文本编辑器-->
    <script>
    layui.use(['tinymce', 'form', 'jquery'], function () {
    let form = layui.form;
    let $ = layui.jquery;

    //富文本编辑器
    var tinymce = layui.tinymce
    var edit = tinymce.render({
        elem: "#edit",
        //配置上传接口
        images_upload_url: '../../../../file/upload2',
        form: {
            //配置上传文件的字段名称
            name: 'file',
        },
        height: 400,
    });
    //获取文本框中的值
    edit.getContent();
    console.log(edit.getContent());

    // 数据提交(../../../../admin/addarticle)
    form.on('submit(form-fabu)', function (data) {
        //将文本框内的值赋值给data.field.article_content
        data.field.article_content = edit.getContent()
        console.log(data.field.article_content)
        let roleIds = "";
        $('input[type=checkbox]:checked').each(function () {
            roleIds += $(this).val() + ",";
        });
        roleIds = roleIds.substr(0, roleIds.length - 1);
        data.field.roleIds = roleIds;
        console.log(data.field);
        $.ajax({
            url: '../../../../admin/addarticle',
            data: JSON.stringify(data.field),
            dataType: 'json',
            contentType: 'application/json',
            type: 'post',
            success: function (result) {
                if (result.success) {
                    layer.msg(result.msg, {icon: 2, time: 1000});
                } else {
                    layer.msg(result.msg, {icon: 1, time: 1000});
                }
            }
        })
        return false;
    });
})
</script>

步骤三、自定义AjaxUploadResponse响应体

@Data
@AllArgsConstructor
@NoArgsConstructor

public class AjaxUploadResponse<T> {
    private int code = 0;
    private String msg = "";
    private String data = "";
}

步骤四、编写文件上传控制器

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload1")
    public AjaxUploadResponse uploadfile(@RequestParam("file") Part file, HttpServletRequest request) {
        // 文件名
        System.out.println("文件名" + file.getContentType());
        // 将file上传到服务器的指定位置(webapp下的某个目录)
        String realPath = request.getRealPath("/");
        System.out.println("realPath:" + realPath);
        String fileName = (realPath + "/img/" + file.getSubmittedFileName());
        try {
            file.write(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        AjaxUploadResponse uploadResponse = new AjaxUploadResponse(0, "上传成功", "/img/" + file.getSubmittedFileName());
        return uploadResponse;
    }


    @PostMapping("upload2")
    public AjaxUploadResponse uploadfile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 文件类型
        System.out.println(file.getContentType());
        // 文件名
        System.out.println(file.getOriginalFilename());
        // 将file上传到服务器的指定位置(webapp下的某个目录)
        String realPath = request.getRealPath("/");
        System.out.println("realPath:" + realPath);
        File dest = new File(realPath+"/img/"+file.getOriginalFilename());
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        AjaxUploadResponse uploadResponse = new AjaxUploadResponse(0, "上传成功", "/img/" + file.getOriginalFilename());
        return uploadResponse;
    }
}

步骤五、实现文章新增功能

1、Dao层

@Override
public boolean addArticle(ArticleEntity article) {
    String sql = "INSERT INTO g_article VALUES (NULL,?,?,'imgtest.jpg','悟空网',?,0,NOW(),0)";
    return DBUtil.exUpdate(sql, article.getArticle_title(), article.getArticle_content(), article.getActicle_type()) > 0;
}

2、Service层

@Override
public boolean addArticle(ArticleEntity article) {
    return articleDao.addArticle(article);
}

3、Controller层

@PostMapping("/addarticle")
public AjaxOperateResponse addArticle(@RequestBody ArticleEntity article) {
    AjaxOperateResponse response = new AjaxOperateResponse(200, articleService.addArticle(article) ? "增加成功" : "增加失败");
    return response;
}

4、AjaxOperateResponse

@Data
@AllArgsConstructor
@NoArgsConstructor
public class AjaxOperateResponse<T> {
    private int code = 0;
    private String msg;
}

步骤六、最终运行效果

图片上传成功:

文章内容新增成功:

数据库添加成功:

最后修改:2021 年 08 月 30 日 02 : 01 AM
如果觉得我的文章对你有用,请随意赞赏