Maven引入百度编辑器依赖:
<dependency>
<groupId>com.baidu</groupId>
<artifactId>ueditor</artifactId>
<version>1.1.2</version>
</dependency>
界面:
<dd>
<label for="content">内 容:</label>
<script id="editor" name="content" type="text/plain" style="width: 100%;height:100%">${article.content}</script>
<script type="text/javascript">
var ue = UE.getEditor('editor',{
//focus时自动清空初始化的内容
autoClearinitialContent:false,
//开启字数统计
worrdCount:true,
//默认编辑区域的高度
initialFrameWidth:820,
//默认编辑区域的高度
initialFrameHeight:280
});
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
//判断路径 这里是config.json 中设置执行上传的action名称
if (action == 'uploadimage') {
return '${ctx}/ueditor/uploadImg';
} else if (action == 'uploadvideo') {
return '${ctx}/ueditor/uploadVideo';
} else if (action == 'downloadImage') {
return '${ctx}/"'+imgName+'"/getImage';
} else {
return this._bkGetActionUrl.call(this, action);
}
}
</script>
</dd>
图片类:
/**
* 图片辅助类
*/
public class ImgUtil {
/**
* 从HTML源码中提取图片路径,最后以一个 String 类型的 List 返回,如果不包含任何图片,则返回一个 size=0 的List
* 需要注意的是,此方法只会提取以下格式的图片:.jpg|.bmp|.eps|.gif|.mif|.miff|.png|.tif|.tiff|.svg|.wmf|.jpe|.jpeg|.dib|.ico|.tga|.cut|.pic
* @param htmlCode HTML源码
* @return <img>标签 src 属性指向的图片地址的List集合
* @author Carl He
*/
public static List<String> getImageSrc(String htmlCode) {
List<String> imageSrcList = new ArrayList<String>();
Pattern p = Pattern.compile("<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(htmlCode);
String quote = null;
String src = null;
while (m.find()) {
quote = m.group(1);
src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("\\s+")[0] : m.group(2);
imageSrcList.add(src);
}
return imageSrcList;
}
}
Controller:
@RequestMapping("/addArticle")
public void addArticle(@ModelAttribute ArticleDto articleDto, HttpServletRequest request,HttpServletResponse response) throws Exception{
List<String> list = ImgUtil.getImageSrc(request.getParameter("content"));
if(CollectionUtils.isNotEmpty(list)) {
articleDto.setImg(list.get(0));
}
articleDto.setIsDelete(0);
articleDto.setCollectNum(0);
articleDto.setReadNum(0);
articleDto.setReplyNum(0);
articleDto.setWeight(0);
articleDto.setCreateTime(new Date());
articleDto.setUpdateTime(new Date());
articleDto.setPublishTime(new Date());
adminArticleService.addArticle(articleDto);
}
ServiceImp:
@Override
public boolean addArticle(ArticleDto articleDto) {
if(articleDto == null){
return false;
}
try {
int rs = adminArticleDtoMapper.insertAndReturnId(articleDto);
if(rs == 0){
return false;
}
if(StringUtils.isNotBlank(articleDto.getContent())){
ArticleDetailDto detail = new ArticleDetailDto();
detail.setArticleId(articleDto.getId());
detail.setContent(articleDto.getContent());
detail.setMain(articleDto.getTitle());
detail.setCreateTime(articleDto.getCreateTime());
articleDetailDtoMapper.insert(detail);
}
return true;
}catch(Exception e) {
logger.error("添加文章异常,文章内容为:{},异常原因:{}",JSONObject.toJSONString(articleDto),e);
return false;
}
}
Mapper.xml:
和正常的添加一样
UEditor控制类
@Controller
@RequestMapping("/ueditor")
public class UEditorController {
private static Logger log = LoggerFactory.getLogger(UEditorController.class);
@Resource
private AdminArticleService adminArticleService;
@Resource
private CommonAreaDtoService commonAreaDtoService;
@Resource
private AdminCategoryService adminCategoryService;
@Resource(name="ossFile")
private OssFile ossFile;
/**
* 上传文件
* @param upfile
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> uploadImage(@RequestParam("upfile") MultipartFile upfile,HttpServletRequest request) throws IOException{
//文件原名称
String fileName=upfile.getOriginalFilename();
//为了避免重复简单处理
String nowName=new Date().getTime()+"_" + fileName;
Map<String, Object> result = Maps.newHashMap();
String originalName = "";
String finalName = "";
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next().toString());
finalName = ossFile.uploadImageOss(file);
if(StringUtils.isEmpty(finalName)){
finalName = ossFile.uploadImageLocal(file);
}
}
}
result.put("state", "SUCCESS");
result.put("msg", "上传成功");
result.put("originalName",originalName);
result.put("title",finalName);
result.put("url",finalName);
return result;
}
/**
* 读取文件
*/
@RequestMapping("{imgName}/getImage")
public void readImg(@PathVariable("imgName") String imgName,@RequestParam("upfile") CommonsMultipartFile upfile, HttpServletRequest request, HttpServletResponse response) throws Exception {
//设置文件的返回类型
response.setContentType("image/*");
//文件路径(windows下是\\,linux下是//,都必须是绝对路径)
String imgPath=UrlUtil.ADMIN_DOMNUPLOAD_IMG.getUrl()+imgName;
//String imgPath="E:\\upload\\image\\"+imgName;
//java中用File类来表示一个文件
File image = new File(imgPath);
//测试这个文件路径是否存在(也就是这个文件是否存在)
if (!image.exists()) {
return;
}
request.getSession().setAttribute("imgPath", imgPath);
//FileUtils.readFileToByteArray(File file)把一个文件转换成字节数组返回
response.getOutputStream().write(FileUtils.readFileToByteArray(image));
//java在使用流时,都会有一个缓冲区,按一种它认为比较高效的方法来发数据:
//把要发的数据先放到缓冲区,缓冲区放满以后再一次性发过去,而不是分开一次一次地发.
//而flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满.
response.getOutputStream().flush();
response.getOutputStream().close();
}
/**
* 上传视频
* @param upfile
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = "/uploadvideo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,String> uploadvideo(@RequestParam("upfile") CommonsMultipartFile upfile,HttpServletRequest request) throws IOException{
//文件原名称
String fileName=upfile.getOriginalFilename();
//为了避免重复简单处理
String nowName=new Date().getTime()+"_" + fileName;
//上传位置路径
String path0 = UrlUtil.ADMIN_UPLOAD_IMG.getUrl()+nowName;
// String path0="E:\\upload\\video\\"+nowName;
//按照路径新建文件
File newFile = new File(path0);
//复制
FileCopyUtils.copy(upfile.getBytes(), newFile);
//返回结果信息(UEditor需要)
Map<String,String> map = new HashMap<String,String >();
//是否上传成功
map.put("state", "SUCCESS");
//现在文件名称
map.put("title", nowName);
//文件原名称
map.put("original", fileName);
//文件类型 .+后缀名
map.put("type", fileName.substring(upfile.getOriginalFilename().lastIndexOf(".")));
//文件路径
map.put("url", "/"+nowName);
//文件大小(字节数)
map.put("size", upfile.getSize()+"");
return map;
}
/**添加新闻
*
* @param articleDto
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/addArticle")
public void addArticle(@ModelAttribute ArticleDto articleDto, HttpServletRequest request,HttpServletResponse response) throws Exception{
List<String> list = ImgUtil.getImageSrc(request.getParameter("content"));
if(CollectionUtils.isNotEmpty(list)) {
articleDto.setImg(list.get(0));
}
articleDto.setIsDelete(0);
articleDto.setCollectNum(0);
articleDto.setReadNum(0);
articleDto.setReplyNum(0);
articleDto.setWeight(0);
articleDto.setCreateTime(new Date());
articleDto.setUpdateTime(new Date());
articleDto.setPublishTime(new Date());
adminArticleService.addArticle(articleDto);
}
/*
* 修改
*/
@RequestMapping("/update")
public void update(@ModelAttribute ArticleDto articleDto ,
HttpServletRequest request, HttpServletResponse response)throws Exception{
List<String> list = ImgUtil.getImageSrc(request.getParameter("content"));
if(CollectionUtils.isNotEmpty(list)) {
articleDto.setImg(list.get(0));
}
articleDto.setUpdateTime(new Date());
/*
* 修改的时候
* 如果是未删除 则可以选:已删除、未发布、已发布【jsp页面控制】
* 如果是已删除 则可以选:未删除(同时修改status状态为:未发布)【后台控制】
*/
if(articleDto.getIsDelete()==1){
articleDto.setStatus(0);
}
adminArticleService.update(articleDto);
}
//获取所有的行政区
@ResponseBody
@RequestMapping("/getProvince")
public List<CommonAreaDto> getProvince(HttpServletRequest request,HttpServletResponse response,
@RequestParam(value="parentId",defaultValue="0",required=false)Long parentId,CommonAreaDto commonAreaDto){
List<CommonAreaDto> list = commonAreaDtoService.getProvince(parentId);
return list;
}
/**
* 查询类目
* @param request
* @param response
* @param commonCategoryDto
* @return
*/
@ResponseBody
@RequestMapping("category")
public List<CommonCategoryDto> category(HttpServletRequest request,HttpServletResponse response,CommonCategoryDto commonCategoryDto){
List<CommonCategoryDto> list = adminCategoryService.getCategory();
request.setAttribute("data", list);
return list;
}
}
上传图片类:
public class OssFile {
private static final Logger logger = LoggerFactory.getLogger(OssFile.class);
private static final String IMAGE_PATH = "/img/";
private static final String IMAGE_FORMAT = "png";
private String domain;
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private OSSClient client;
private String defaultDomain;
/**
* 上传图片
* @return
*/
public String uploadImageOss(MultipartFile file){
if(file == null){
return null;
}
client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
Calendar c = Calendar.getInstance();
String finalName = "";
try{
String originalName = file.getOriginalFilename();
//String dir = c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/";
String dir = "admin-img/";
//拼凑文件名称,不能拼成http://这种
String postfix = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
finalName = dir + c.getTimeInMillis() + "." + postfix;
PutObjectResult result = client.putObject(bucketName, finalName, file.getInputStream());
}catch(Exception e){
logger.info("上传文件失败!");
return null;
}finally{
client.shutdown();
}
return domain +"/" + finalName;
}
/**
* 上传图片
* @return
*/
public String uploadImageOssAPP(MultipartFile file){
if(file == null){
return null;
}
client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
Calendar c = Calendar.getInstance();
String finalName = "";
try{
String originalName = file.getOriginalFilename();
//String dir = c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/";
String dir = "web-img/";
//拼凑文件名称,不能拼成http://这种
String postfix = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
finalName = dir + c.getTimeInMillis() + "." + postfix;
PutObjectResult result = client.putObject(bucketName, finalName, file.getInputStream());
}catch(Exception e){
logger.info("上传文件失败!");
return null;
}finally{
client.shutdown();
}
return domain +"/" + finalName;
}
/**
* 上传图片
* @return
*/
public String uploadInputStreamOss(InputStream inputStream){
if(inputStream == null){
return null;
}
client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
Calendar c = Calendar.getInstance();
String finalName = "";
try{
//拼凑文件名称,不能拼成http://这种
//String dir = c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/";
String dir = "admin-img/";
finalName =dir + c.getTimeInMillis() + "." + IMAGE_FORMAT;
PutObjectResult result = client.putObject(bucketName, finalName, inputStream);
// System.out.println("result:" + JSONObject.toJSONString(result));
}catch(Exception e){
logger.info("上传文件失败!");
return null;
}finally{
client.shutdown();
}
return domain +"/" +finalName;
}
/**
* 上传图片
* @return
*/
public String uploadInputStreamOssAPP(InputStream inputStream){
if(inputStream == null){
return null;
}
client = new OSSClient(endpoint,accessKeyId, accessKeySecret);
Calendar c = Calendar.getInstance();
String finalName = "";
try{
//拼凑文件名称,不能拼成http://这种
//String dir = c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/";
String dir = "web-img/";
finalName =dir + c.getTimeInMillis() + "." + IMAGE_FORMAT;
PutObjectResult result = client.putObject(bucketName, finalName, inputStream);
// System.out.println("result:" + JSONObject.toJSONString(result));
}catch(Exception e){
logger.info("上传文件失败!");
return null;
}finally{
client.shutdown();
}
return domain +"/" +finalName;
}
public String uploadImageLocal(MultipartFile file){
String originalName = "";
String finalName = "";
if (file == null) {
return null;
}
//创建目录
Calendar c = Calendar.getInstance();
//String dir = defaultDomain + IMAGE_PATH + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/";
String dir = defaultDomain + "admin-img/";
File dirFile = new File(dir);
if(!dirFile.isDirectory()){
dirFile.mkdirs();
}
//拼凑文件名称
originalName = file.getOriginalFilename();
String postfix = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
finalName =dir + c.getTimeInMillis() + "." + postfix;
try {//写入文件
file.transferTo(new File(finalName));
} catch (IllegalStateException e) {
logger.error(e.getMessage());
return null;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
}
return finalName;
}
public String uploadImageLocalAPP(MultipartFile file){
String originalName = "";
String finalName = "";
if (file == null) {
return null;
}
//创建目录
Calendar c = Calendar.getInstance();
//String dir = defaultDomain + IMAGE_PATH + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/";
String dir = defaultDomain + "/web-img/";
File dirFile = new File(dir);
if(!dirFile.isDirectory()){
dirFile.mkdirs();
}
//拼凑文件名称
originalName = file.getOriginalFilename();
String postfix = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
finalName =dir + c.getTimeInMillis() + "." + postfix;
try {//写入文件
file.transferTo(new File(finalName));
} catch (IllegalStateException e) {
logger.error(e.getMessage());
return null;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
}
return finalName;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getDefaultDomain() {
return defaultDomain;
}
public void setDefaultDomain(String defaultDomain) {
this.defaultDomain = defaultDomain;
}
}