教程文档地址:
UEditor Docs
为什么要使用UEditor,用于替换掉textarea(纯文本编辑器),只因为富文本编辑器样式丰富,所以使用它
解压ueditor1_4_3_3-utf8-jsp.zip后在项目中使用:
压缩包:
链接:百度网盘 请输入提取码
提取码:7777
在该页面的添加下(goods-add.ftl)引入UEditor的核心js文件:
<!-- 百度 ueditor -->
<script type="text/javascript" charset="utf-8" src="${ctx}/plugins/Ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="${ctx}/plugins/Ueditor/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="${ctx}/plugins/Ueditor/lang/zh-cn/zh-cn.js"></script>
初始化编辑器并实例化:
<!--以下是在线编辑器 代码 -->
<script type="text/javascript">
/*
* 在线编辑器相 关配置 js
* 参考 地址 http://fex.baidu.com/ueditor/
*/
window.UEDITOR_Admin_URL = "${ctx}/plugins/Ueditor/";
var URL_upload = "/index/Admin/Ueditor/imageUp/savepath/goods";
var URL_fileUp = "/index/Admin/Ueditor/fileUp/savepath/article";
var URL_scrawlUp = "/index/Admin/Ueditor/scrawlUp/savepath/article";
var URL_getRemoteImage = "/index/Admin/Ueditor/getRemoteImage/savepath/article";
var URL_imageManager = "/index/Admin/Ueditor/imageManager/savepath/article";
var URL_imageUp = "/index/Admin/Ueditor/imageUp/savepath/article";
var URL_getMovie = "/index/Admin/Ueditor/getMovie/savepath/article";
var URL_home = "";
</script>
<script type="text/javascript">
var editor;
$(function () {
//具体参数配置在 editor_config.js 中
//通过修改options来定制UEditor的内容
var options = {
zIndex: 999,
initialFrameWidth: "95%", //初化宽度
initialFrameHeight: 400, //初化高度
focus: false, //初始化时,是否让编辑器获得焦点true或false
maximumWords: 99999,
removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign', //允许的最大字符数 'fullscreen',
pasteplain: false, //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴
autoHeightEnabled: true
/* autotypeset: {
mergeEmptyline: true, //合并空行
removeClass: true, //去掉冗余的class
removeEmptyline: false, //去掉空行
textAlign: "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
pasteFilter: false, //根据规则过滤没事粘贴进来的内容
clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
removeEmptyNode: false, //去掉空节点
//可以去掉的标签
removeTagNames: {"font": 1},
indent: false, // 行首缩进
indentValue: '0em' //行首缩进的大小
}*/,
toolbars: [
['fullscreen', 'source', '|', <!--撤销-->'undo', <!--重做-->'redo',
'|', 'bold', 'italic', 'underline', 'fontborder',
'strikethrough', 'superscript', 'subscript',
'removeformat', 'formatmatch', 'autotypeset',
'blockquote', 'pasteplain', '|', 'forecolor',
'backcolor', 'insertorderedlist',
'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize',
'|', 'directionalityltr', 'directionalityrtl',
'indent', '|', 'justifyleft', 'justifycenter',
'justifyright', 'justifyjustify', '|', 'touppercase',
'tolowercase', '|', 'link', 'unlink', 'anchor', '|',
'imagenone', 'imageleft', 'imageright', 'imagecenter',
'|', 'insertimage', 'emotion', 'insertvideo',
'attachment', 'map', 'gmap', 'insertframe',
'insertcode', 'webapp', 'pagebreak', 'template',
'background', '|', 'horizontal', 'date', 'time',
'spechars', 'wordimage', '|',
'inserttable', 'deletetable',
'insertparagraphbeforetable', 'insertrow', 'deleterow',
'insertcol', 'deletecol', 'mergecells', 'mergeright',
'mergedown', 'splittocells', 'splittorows',
'splittocols', '|', 'print', 'preview', 'searchreplace']
]
};
editor = new UE.ui.Editor(options);
// 指定 textarea 的 id 为 goods_content
editor.render("goodsContent");
});
</script>
<!--以上是在线编辑器 代码 end-->
最后更改商品的详情描述中的即可:
<tr>
<td>商品详情描述:</td>
<td width="85%">
<textarea rows="6" cols="80" class="span12 ckeditor" id="goodsContent" name="goodsContent" title=""></textarea>
<span id="err_goods_content" style="color:#F00; display:none;"></span>
</td>
</tr>
bootstrap文件上传工具的使用
部署环境:
引入css和js:goodsCategory-add.ftl
<link rel="stylesheet" href="${ctx}/css/fileinput.min.css"></link>
<script type="text/javascript" src="${ctx}/js/fileinput.js"></script>
<!-- 对中文的支持 -->
<script type="text/javascript" src="${ctx}/js/fileinput_locale_zh.js"> </script>
<script type="text/javascript">
在分类展示图片中添加一个form表单:
并设置image的隐藏域
<form enctype="multipart/form-data">
<!--文件上传成功的地址的隐藏域-->
<input type="hidden" id="image" name="image" />
<input id="file-goods-category" class="file" name="file" type="file" data-min-file-count="1">
</form>
添加js、调用文件上传的插件
//加入文件上传的代码 BootStrap文件的上传
/*** 初始设置
* language指定语言
* uploadUrl指定文件上传的后台地址
* allowedPreviewTypes允许上传文件的类型
*/
$('#file-goods-category').fileinput({
language: 'zh',
uploadUrl: '${ctx}/fileUpload/save',
allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash']
});
/***
上传文件失败后 调用方法(回调函数)
*/
$('#file-goods-category').on('fileuploaderror', function (event, data, previewId, index) {
var form = data.form,
files = data.files, e
xtra = data.extra,
response = data.response,
reader = data.reader;
console.log(data);
console.log('File upload error');
});
/**
* 文件错误 比如文件类型错误 调用方法(回调函数)
*/
$('#file-goods-category').on('fileerror', function (event, data) {
console.log(data.id);
console.log(data.index);
console.log(data.file);
console.log(data.reader);
console.log(data.files);
});
/**
* 文件上传成功后 调用方法(回调函数)
*/
$('#file-goods-category').on('fileuploaded', function (event, data, previewId, index) {
var form = data.form,
files = data.files,
extra = data.extra,
response = data.response,
reader = data.reader;
// 服务器文件地址
// alert(data.response.fileUrl);
// 将服务器文件地址设置至隐藏域
$("#image").val(data.response.fileUrl);
console.log('File uploaded triggered');
});
后端代码的实现:
shop-manager: pom.xml:
<!-- 七牛云sdk 依赖-->
<qiniu.version>[7.2.0, 7.2.99]</qiniu.version>
<!--七牛云SKD-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>${qiniu.version}</version>
</dependency>
shop-common:pom.xml:
<!-- 七牛云sdk 依赖 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
</dependency>
在shop-common的包下创建一个result包,再创建FileResult
public class FileResult implements Serializable {
// success字符串bootstrap file input必须包含该属性
private String success;
// error字符串bootstrap file input必须包含该属性
private String error;
// 描述信息
private String message;
// 文件路径
private String fileUrl;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}
shop-manager:application.yml:
# Spring
spring:
servlet:
multipart:
# 单个文件上限
max-file-size: 100MB
# 单次请求所有文件总上限
max-request-size: 1000MB
qiniu:
ak: 你的ak
sk: 你的sk
bucket: 你的bucket
Service服务层:
IUploadService
/*** 上传服务 */
public interface IUploadService {
public FileResult uploadFile(InputStream is,String fileName);
}
实现类:
@Service
public class UploadServiceImpl implements IUploadService {
@Value("${qiniu.ak}")
private String accessKey;
@Value("${qiniu.sk}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
// @Value("${qiniu.domain}")
// private String domain;
@Override
public FileResult uploadFile(InputStream is, String fileName) {
System.out.println("fileName = " + fileName);
FileResult fileResult = new FileResult();
try {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
Response response = uploadManager.put(is, fileName, upToken, null, null);
if (response.isOK()) {
fileResult.setSuccess("文件上传成功!");
fileResult.setFileUrl("http://r0nr0baxe.hd-bkt.clouddn.com/" + fileName);
}
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
fileResult.setError("文件上传失败!");
}
return fileResult;
}
}
Controller:控制层
UploadController:
@Controller
public class UploadController {
@Resource
private IUploadService uploadService;
//文件上传
@RequestMapping("fileUpload/save")
@ResponseBody
public FileResult uploadFile(@RequestParam(name = "file") MultipartFile file){
FileResult fielResult=new FileResult();
//先判断是否为空
if (file.isEmpty()){
fielResult.setError("文件内容不能为空");
return fielResult;
}
try{
String fileName=file.getOriginalFilename();
fileName=new SimpleDateFormat("yyy/MM/dd").format(new Date())
+"/"+System.currentTimeMillis()
+fileName.substring(fileName.lastIndexOf("."));
fielResult=uploadService.uploadFile(file.getInputStream(),fileName);
}catch (IOException e){
e.printStackTrace();
fielResult.setError("文件上传失败");
return fielResult;
}
return fielResult;
}
}
前台接收:
/**
* 文件上传成功后 调用方法(回调函数)
*/
$('#file-goods-category').on('fileuploaded', function (event, data, previewId, index) {
var form = data.form,
files = data.files,
extra = data.extra,
response = data.response,
reader = data.reader;
// 服务器文件地址
alert(data.response.fileUrl);
// 将服务器文件地址设置至隐藏域
$("#originalImg").val(data.response.fileUrl);
console.log('File uploaded triggered');
});
如果出现图片上显示为空,则需要修改fileinput.js中1314行:
改为:if(!idea.error)