其实做起来分为这个几部
1.先获取到你所复制的HTML代码内容
2.通过正则表达式获取到img标签中的src地址
3.将获取到的地址通过ajax传到后台进行下载,并将保存后的地址返回到前台
4.获取后台返回的url进行替换
5.调用kindeditor编辑器的同步函数 将源码和HTML展示的内容进行同步,不然有时候你会发现你明明已经将url进行了替换,但是保存后却还是远程地址。
具体代码前台JS代码:
function uploadpic(img) {
$("#image-loading-modal").modal({
backdrop : 'static'
});
var img = $(".ke-edit-iframe").contents().find("img");
$(img).each(function (i) {
var that = $(this);
if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {
$.ajax({
url: lm.global.server+"upload/remoteImage",
data: "imgUrl=" + that.attr("src").split("?")[0],
type: "POST",
dataType: "json",
async: false,
success: function (data) {
that.attr("src",data.url);
that.attr("data-ke-src",data.url);
}
});
}
});
editor.sync(); //同步函数
}
我这里是一张张图片上传的,有需要的话可以将所有图片地址全部获取到后,一次性全部上传
后台JAVA代码:
/**
* 下载图片
* @param urlString
* @param filename
* @throws Exception
*/
@ResponseBody
@RequestMapping("upload/remoteImage")
public String remoteImage(String imgUrl,HttpServletRequest request, HttpServletResponse response) {
InputStream is = null;
OutputStream os = null;
String name=null;
// 文件保存目录路径
String savePath = context.getRealPath("/")+"/attached/";
// 文件保存目录URL
String saveUrl = request.getContextPath() + "/attached/";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath=savePath+ymd+"/";
saveUrl=saveUrl+ymd+"/";
response.setContentType("text/html; charset=UTF-8");
try {
// 构造URL
URL url = new URL(imgUrl);
// 打开连接
URLConnection con = url.openConnection();
// 设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
//新文件名称
String fileExt = FileExtUtils.fileSuffix(imgUrl);
name = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_"+ new Random().nextInt(1000) + "." + fileExt;
Path path = Paths.get(savePath);
if (!Files.isDirectory(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
throw new UploadException("上传附件时,创建文件夹错误:"+path);
}
}
os = new FileOutputStream(savePath+"/"+name);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
throw new UploadException("上传附件,保存文件到服务器失败:" + savePath + name);
} finally {
try {
// 完毕,关闭所有链接
if (os != null) {
os.close();
}
if(is!=null){
is.close();
}
} catch (Exception e2) {
}
}
KindeditorResult result = new KindeditorResult(0,saveUrl+name,"保存成功");
result.setFileName(name);
result.setRealPath(savePath+name);
return JSON.toJSONString(result);
}