KindEditor实现跨域访问接口问题(图片上传)

写一个项目,需要使用富文本,于是选择了KindEditor。
遇到KindEditor前端访问后端接口时的跨域问题,主要体现在图片上传上。

1.KindEditor下载http://kindeditor.net/down.php
下载后自行删除无用文件,保留这几个就行。
在这里插入图片描述
话不多说,上代码。
index.html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<!--导入在线HTML编辑器 -->
		<link rel="stylesheet" href="themes/default/default.css" />
		<script type="text/javascript" src="kindeditor-all-min.js" ></script>
		<script type="text/javascript" src="jquery-3.4.1.min.js" ></script>
	    <script language="JavaScript" type="text/javascript">
			var editor;

			var callBackPath = 'http://127.0.0.1:8848/KindEditorDemo/redirect.html';
			    KindEditor.ready(function(K) {
			        editor = K.create('#addeditor', {
			        	items:[
	                        'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
	                        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
	                        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
	                        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', '/',
	                        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
	                        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
	                        'table', 'hr',  'link', 'unlink'
	                   ],
			            minHeight:'350px',
			            allowFileManager : true,
			            uploadJson: 'http://localhost:8083/save_photo?callBackPath='+callBackPath,
			            afterUpload: function(url, data, name) {
			                if(name === 'insertfile'){
			                    $("#keTitle").val(data.filename);
			                }
			                console.log(url);
			                console.log(data);
			                console.log(name);
			    		}
			      })
		    editor.insertHtml("没有数据");
		 });
		 function save(){
		     editor.sync();
		     html=document.getElementById('addeditor').value;
		     $("#schtmlnr").val(html);
		     alert($("#schtmlnr").val());
		 }	
	</script>
	</head>
	<body>
	 <form>
	   <textarea id="addeditor" name="content" style="width:50%;height:400px;border: 0 none;visibility:hidden;"></textarea>
	   <textarea rows="" cols="" name="schtmlnr" id="schtmlnr" style="display:none;"></textarea>
	 </form>
	 <input name="" type="button" class="btn" onclick="save()" value="确认"/>
	</body>
	</html>
	
</html>

在这里插入图片描述

redirect.html:
重定向页面,解决跨域的关键。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ie </title>
    <script type="text/javascript">
    function getParameter(val) {
        var uri = decodeURI(window.location.search);
        var re = new RegExp("" + val + "=([^&?]*)", "ig");
        return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : '123');
    }

        var upload_callback = function() {
            var error = getParameter("error");
            error = parseInt(error)
            var dataObject;
            if(error==0){
                var url = getParameter("url");
                dataObject = {"error": error, "url": url};
            }else{
                var message = getParameter("message");
                dataObject = {"error": error, "message": message};
            }
            var data =  JSON.stringify(dataObject)
            document.getElementsByTagName("body")[0].innerHTML = '<pre>' + data + '</pre>';
        }
    </script>
</head>
<body onload="upload_callback();">
</body>
</html>

后台接口http://localhost:8083/save_photo:
文件格式是这样的,默认你会SpringBoot。
在这里插入图片描述
代码:

package com.example.demo.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@CrossOrigin

public class TestController {

    @RequestMapping(path = "/save_photo", method = {RequestMethod.POST})
    public Map  addDish(@RequestParam("imgFile") MultipartFile imgFile, HttpServletResponse response,HttpServletRequest request,@RequestParam String callBackPath) throws Exception {
    	Map map=new HashMap();
    	String returnUrl;
        String fileName = imgFile.getOriginalFilename();// 文件原名称
    	String path = null;// 文件路径
        double fileSize = imgFile.getSize();
        System.out.println("文件的大小是"+ fileSize);
        byte[] sizebyte=imgFile.getBytes();
        System.out.println("文件的byte大小是"+ sizebyte.toString());
        if (imgFile != null) {// 判断上传的文件是否为空
            String type = null;// 文件类型
            System.out.println("上传的文件原名称:" + fileName);
            // 判断文件类型
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空
 
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                    // 设置存放图片文件的路径
                    path = "C:\\Users\\Hanqy\\eclipse-workspace\\Test\\src\\main\\resources\\static\\images\\"+fileName;
                    System.out.println("存放图片文件的路径:" + path);
                    // 转存文件到指定的路径
                    imgFile.transferTo(new File(path));
                    //数据库里存"http://localhost:8083/images/"+fileName这个路径就好,因为配置文件有映射
                    map.put("error", 0);
                    map.put("url", "http://localhost:8083/images/"+fileName);
                    response.sendRedirect(callBackPath+"?error=0&url="+"http://localhost:8083/images/"+fileName);
                    return null;
                }
            } else {
                System.out.println("不是我们想要的文件类型,请按要求重新上传");
                map.put("error", 1);
                response.sendRedirect(callBackPath+ "?error=1&message="+"错误信息");
                return null;
            }
        } else {
        	   map.put("error", 1);
        	   response.sendRedirect(callBackPath+ "?error=1&message="+"错误信息");
               return null;
        }
        map.put("error", 0);
        map.put("url", "http://localhost:8083/images/"+fileName);
        
        response.sendRedirect(callBackPath+"?error=0&url="+"http://localhost:8083/images/"+fileName);
        return null;
    }
    }

注意:
在这里插入图片描述

在这里插入图片描述

配置代码:

server.port=8083

filePath=C:\\Users\\Hanqy\\eclipse-workspace\\Test\\src\\main\\resources\\static\\

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${filePath}

运行服务器,运行前端。
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述在这里插入图片描述
点击确定后
在这里插入图片描述
在这里插入图片描述
好了,到此结束了。帮到你的话,记得点赞!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值