解决问题:1、服务器之前来回的挂载
2、图片上传后经过编辑器被压缩
版本信息:ckeditor_4.11.1_full
下载地址:https://ckeditor.com/ckeditor-4/download/
1、将ckeditor放入项目的静态文件夹中
2、打开ckeditor/plugins/image/dialogs/image.js文件,搜索“b.config.image_previewText”,(b.config.image_previewText||'')单引号中的内容全删了,
搜索“upload”可以找到这一段 id:'Upload',hidden:true实际上上传功能被隐藏了,把上面的true改成false,如果你的显示是hidden:!0,直接改成0即可,就可以显示了,再打开编辑器,就能找到上传功能了。
3、ckeditor/config.js文件设置上传到服务器按钮的事件URL,指定将上传的文件提交给那个URL进行处理
代码:
```package com.puyitou.web.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
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.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.alibaba.fastjson.JSON;
import com.puyitou.common.HttpClientUtil;
import com.puyitou.common.util.UploadFileUtil;
import com.puyitou.web.controller.BaseController;
/**
* 用于CKEditor编辑器上传
*
* @author XML
* @Description:
* @date: 2018年11月21日 上午11:21:37
*/
@Controller
public class CKEditorUploadController extends BaseController {
private static Logger logger = Logger.getLogger(CKEditorUploadController.class);
private static Long MAX_IMG_SIZE = 1048576L;
private static List<String> ImageTypes = new ArrayList<String>(Arrays.asList(".jpg",".jpeg",".bmp",".gif",".png"));// 图片类型
private static List<String> viodeTypes = new ArrayList<String>(Arrays.asList(".mp3",".avi",".mov",".asf",".rm",".mpeg"));// 视频类型
private static String TX_TARGET_ROUTE = "file/";//腾讯对象存储所在文件夹
private static String LOCAL_TARGET_ROUTE = "/mydata/PYTFileMng/upload/";//本地图片下载路径
private static String SHOW_URL = "";//腾讯虚拟路径
private static String REQUEST_URL = "";//调用pyt-service-cm时路径地址
static{
try {
Properties prop = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
FileInputStream in = new FileInputStream(path + "basic.properties");
prop.load(in);
REQUEST_URL = prop.getProperty("request_url");
SHOW_URL = prop.getProperty("show_url");
MAX_IMG_SIZE = prop.getProperty("max_img_size")==null?1048576L:Long.valueOf(prop.getProperty("max_img_size"));
in.close();
} catch (FileNotFoundException e) {
logger.error("data.properties文件没有找到:", e);
} catch (IOException e) {
logger.error("读取show_url时发生异常:", e);
}
}
@RequestMapping(value="/ckeditorUpload",method=RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String CKEditorUpload(HttpServletRequest request) throws Exception {
logger.info("上传图片开始");
String type = request.getParameter("type");
System.out.println(type);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("upload");
String fileName = URLDecoder.decode(file.getFileItem().getName(), "UTF-8");
// 获得文件后缀名称,如果后缀不为图片格式,则不上传
String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
//校验文件格式
if("image".equals(type)) {
//图片格式
if(!ImageTypes.contains(suffix)) {
logger.warn("未知的图片类型:" + suffix);
return error(502, "图片类型不符合要求!");
}
//图片大小
if(file.getSize() >= MAX_IMG_SIZE){
logger.warn("图片大小超过限制:" + suffix);
return error(502, "图片大小超过限制(10M)");
}
}else if("flash".equals(type)) {
//视频
if(!viodeTypes.contains(suffix)) {
logger.warn("未知的视频类型:" + suffix);
return error(502, "视频类型不符合要求!");
}
}else{
//未知类型
logger.warn("未知文件的类型:");
return error(502, "文件格式不符合要求!");
}
// 当前日期
String dateTimeStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
// 文件新路径
String newFilePath = "app_find/" + dateTimeStr;
// 检查文件目录
File dirNewPath = new File(LOCAL_TARGET_ROUTE + "/" + newFilePath);
if (!dirNewPath.exists()) {
dirNewPath.mkdirs();
}
//保存文件
String newFileName = UploadFileUtil.saveFile(fileName, file,
LOCAL_TARGET_ROUTE + UploadFileUtil.filesep + newFilePath);
//将文件上传到腾讯的对象存储中
String localUrl = (LOCAL_TARGET_ROUTE + UploadFileUtil.filesep + newFilePath + UploadFileUtil.filesep + newFileName).replaceAll("\\\\", "/");
String destUrl = (TX_TARGET_ROUTE + dateTimeStr + newFileName).replaceAll("\\\\", "/");
Map<String,String> paramMap = new HashMap<String, String>();
paramMap.put("localAddr", localUrl);
paramMap.put("upAddr", destUrl);
paramMap.put("baseAddr", TX_TARGET_ROUTE);
String returnData = HttpClientUtil.doPostJson(REQUEST_URL, JSON.toJSONString(paramMap));
logger.info("返回值:" + returnData);
if(StringUtils.isBlank(returnData)) {
return error(501, "上传文件失败!");
}
logger.info("上传图片结束");
return success("1", fileName,SHOW_URL + destUrl);
}
/**
* CKEditor上传文件所需返回错误格式
* @param code
* @param msg
* @return
*/
public String error(int code, String msg){
Map<String,Object> returnMap = new HashMap<String, Object>();
Map<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put("message",msg);
returnMap.put("uploaded",code);
returnMap.put("error",dataMap);
return JSON.toJSONString(returnMap);
}
/**
* CKEditor上传文件所需返回正确格式
* @param code
* @param msg
* @return
*/
public String success(String uploaded, String fileName,String url){
Map<String,Object> returnMap = new HashMap<String, Object>();
returnMap.put("uploaded",uploaded);
returnMap.put("fileName",fileName);
returnMap.put("url",url);
return JSON.toJSONString(returnMap);
}
}
2腾讯云对象存储
文档地址:https://cloud.tencent.com/document/product/436/14102
介绍:对象存储(Cloud Object Storage,简称:COS)是腾讯云提供的一种存储海量文件的分布式存储服务,用户可通过网络随时存储和查看数据。腾讯云 COS 使所有用户都能使用具备高扩展性、低成本、可靠和安全的数据存储服务。
COS 通过控制台、 API、SDK 等多样化方式简单、快速地接入,实现了海量数据存储和管理。通过 COS 可以进行多格式文件的上传、下载和管理。腾讯云提供了直观的 Web 管理界面,同时遍布全国范围的 CDN 节点可以对文件下载进行加速。
腾讯云对象存储代码:
@Component("tXFileService")
public class TXFileServiceImpl implements TXFileService {
private static Logger logger = LoggerFactory.getLogger(TXFileServiceImpl.class);
private static String LOCAL_TARGET_ROUTE = "/mydata/PYTFileMng/upload/";//本地图片默认下载路径
@Value("${tx.secretId:-1}")
private String secretId;
@Value("${tx.secretKey:-1}")
private String secretKey;
@Value("${tx.bucketName:-1}")
private String bucketName;
@Value("${tx.region:-1}")
private String region;
@Reference
private CmqSendService cmqSendService;
private COSClient getCosClient() {
// 将本地文件上传到COS
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域
ClientConfig clientConfig = new ClientConfig(new Region(region));
// 3 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
return cosclient;
}
@Override
public String uploadImgPubFile(Map<String, Object> paramMap) throws Exception {
COSClient cosClient = getCosClient();
String upAddr = paramMap.get("upAddr").toString();
String oldUpStr = upAddr;
String localAddr = paramMap.get("localAddr").toString();
String baseAddr = paramMap.get("baseAddr").toString();
try {
// 如果上传路径不包含基础路径,则拼接上传路径
if (!upAddr.contains(baseAddr)) {
upAddr = baseAddr + upAddr;
}
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, upAddr, new File(localAddr));
// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
putObjectRequest.setStorageClass(StorageClass.Standard);
cosClient.putObject(putObjectRequest);
return upAddr;
} catch (Exception e) {
logger.error("上传腾讯云对象存储失败:",e);
List<EmailMessageBean> beans = new ArrayList<EmailMessageBean>();
EmailMessageBean bean = new EmailMessageBean();
Map<String,Object> params = new HashMap<>();//请求参数
params.put("upStr", oldUpStr);
params.put("localAddr", localAddr);
params.put("baseAddr", baseAddr);
bean.setParams(params);
bean.setMailType(EmailType.ERROR_EMAIL);//错误邮件
bean.setContent(StringUtils.convertException(e));//错误信息
beans.add(bean);
cmqSendService.sendEmailMessage(beans);
} finally {
// 关闭客户端
cosClient.shutdown();
}
return null;
}
@Override
public String uploadImgPubFileByURL(Map<String, Object> paramMap) throws Exception {
COSClient cosClient = getCosClient();
String upAddr = paramMap.get("upAddr").toString();//腾讯云上传路径
String oldUpStr = upAddr;
String baseAddr = paramMap.get("baseAddr").toString();
String url = paramMap.get("url").toString();//图片地址
String suffix = paramMap.get("suffix").toString();//图片后缀名
String picName = paramMap.get("picName").toString();//图片名称
try{
//将URL图片下载到本地
File file = new File(LOCAL_TARGET_ROUTE + "wechat/acticlepic/" + picName + "." + suffix);
FileUtils.copyURLToFile(new URL(url), file);
// 如果上传路径不包含基础路径,则拼接上传路径
if (!upAddr.contains(baseAddr)) {
upAddr = baseAddr + upAddr;
}
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, upAddr, file);
// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
putObjectRequest.setStorageClass(StorageClass.Standard);
cosClient.putObject(putObjectRequest);
return upAddr;
} catch (Exception e) {
logger.error("上传腾讯云对象存储失败:",e);
List<EmailMessageBean> beans = new ArrayList<EmailMessageBean>();
EmailMessageBean bean = new EmailMessageBean();
Map<String,Object> params = new HashMap<>();//请求参数
params.put("upStr", oldUpStr);
params.put("url", url);
params.put("baseAddr", baseAddr);
bean.setParams(params);
bean.setMailType(EmailType.ERROR_EMAIL);//错误邮件
bean.setContent(StringUtils.convertException(e));//错误信息
beans.add(bean);
cmqSendService.sendEmailMessage(beans);
} finally {
// 关闭客户端
cosClient.shutdown();
}
return null;
}
}