ssm uses rich text box to upload pictures to the database and display to the interface

Realize the effect (Can the audio and word be uploaded before trying)

Insert picture description here
Insert picture description here
The format of inserting the database is like this, it can be taken directly from the database when displaying
Insert picture description here

Implementation steps

1. Download the js
online link that the rich text box plugin depends on
Insert picture description here
2. Introduce js to the page

Insert picture description here
3. Add code

Insert picture description here

<script type="text/javascript">
        var editor;
        KindEditor.ready(function(K) {
    
    
            editor = K.create('textarea[name="content"]', {
    
    
                resizeType: 1,
                uploadJson : '${pageContext.request.contextPath}/fileUpload',// 上传图片接口  项目名(此处项目名是wenjiqiwu)+上传图片的请求路径
                filePostName: 'imgFile',// name属性默认值
                allowPreviewEmoticons: false
            });
        });
    </script>

4. Add rich text box to the interface
Insert picture description here

 新闻内容:
                    <textarea id="addeditor_id" name="content" style="width:100%;height:430px;border: 0 none;visibility:hidden;"></textarea>
                    <textarea rows="" cols="" name="ncontent" id="schtmlnr" style="display:none;"></textarea>

5. Take the value entered in the rich text box

Insert picture description here

//取富文本框输入值
            //先同步
            editor.sync();
            //取值
            var newsContent = ($("#schtmlnr").val($("#addeditor_id").val())).val();

So that you can display the rich text box and get the text of the rich text box

6. Add pom dependency (or jar package)

6.1 Add jar package

Insert picture description here

Insert picture description here
Insert picture description here6.2 Add pom dependencies (some of them may be useless, but try to add them all)

<!--=====================================================================================-->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

7. Write code in the controller

Insert picture description here
Insert picture description here

package com.campus.controller;

import org.springframework.stereotype.Controller;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UploadFileController {
    
    

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public void fileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        //文件保存目录路径
        String savePath = request.getServletContext().getRealPath("/")
                + "upload/";
        System.out.println("文件保存路径 = " + savePath);

        //文件保存目录URL
        String saveUrl = request.getContextPath() + "/upload/";

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        //最大文件大小
        long maxSize = 1000000;

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
    
    
            out = response.getWriter();

            if (!ServletFileUpload.isMultipartContent(request)) {
    
    
                out.println(getError("请选择文件。"));
                return;
            }
            //检查目录
            File uploadDir = new File(savePath);
            if (!uploadDir.isDirectory()) {
    
    
                uploadDir.mkdirs();
            }
            //检查目录写权限
            if (!uploadDir.canWrite()) {
    
    
                out.println(getError("上传目录没有写权限。"));
                return;
            }

            String dirName = request.getParameter("dir");
            if (dirName == null) {
    
    
                dirName = "image";
            }
            if (!extMap.containsKey(dirName)) {
    
    
                out.println(getError("目录名不正确。"));
                return;
            }
            //创建文件夹
            savePath += dirName + "/";
            saveUrl += dirName + "/";
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
    
    
                saveDirFile.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(new Date());
            savePath += ymd + "/";
            saveUrl += ymd + "/";
            File dirFile = new File(savePath);
            if (!dirFile.exists()) {
    
    
                dirFile.mkdirs();
            }

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> itr = multiRequest.getFileNames();
            while (itr.hasNext()) {
    
    
                // 取得上传文件 (遍历)
                MultipartFile file = multiRequest.getFile(itr.next());
                if (file != null) {
    
    
                    // 取得当前上传文件的文件名称
                    String fileName = file.getOriginalFilename();

                    //检查文件大小
                    if (file.getSize() > maxSize) {
    
    
                        out.println(getError("上传文件大小超过限制。"));
                        return;
                    }
                    //检查扩展名
                    String fileExt2 = fileName
                            .substring(fileName.lastIndexOf(".") + 1)
                            .toLowerCase();
                    if (!Arrays.<String>asList(extMap.get(dirName).split(","))
                            .contains(fileExt2)) {
    
    
                        out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许"
                                + extMap.get(dirName) + "格式。"));
                        return;
                    }

                    SimpleDateFormat df2 = new SimpleDateFormat(
                            "yyyyMMddHHmmss");
                    String newFileName2 = df2.format(new Date()) + "_"
                            + new Random().nextInt(1000) + "." + fileExt2;
                    try {
    
    
                        File uploadedFile2 = new File(savePath, newFileName2);
                        file.transferTo(uploadedFile2);
                    } catch (Exception e) {
    
    
                        out.println(getError("上传文件失败。"));
                        return;
                    }

                    JSONObject obj = new JSONObject();
                    obj.put("error", 0);
                    obj.put("url", saveUrl + newFileName2);
                    out.println(obj.toJSONString());
                }
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    private String getError(String message) {
    
    
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toJSONString();
    }
}

8. Then perform a test upload.
You can normally put the selected picture into the rich text box
, click Publish News, you can insert the database normally
, take out the news content on the page, and the picture can also be displayed normally

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41150890/article/details/108686697