Я пытаюсь загрузить изображение в CKEditor с помощью плагина image2. Это нормально, когда я загружаю его с помощью кнопки «Отправить на сервер», но перетаскивание изображений не работает.
Ниже приведена информация о версии:
- Primefaces 6.0
- Ckeditor 4.9.1
- JSF 2.2
config.js
CKEDITOR.editorConfig = function(config){
// config.timestamp='ABCD';
config.disableNativeSpellChecker = false;
config.pasteFromWordRemoveFontStyles=false;
config.pasteFromWordRemoveStyles=false;
config.allowedContent=true;
config.filebrowserBrowseUrl='#{request.contextPath}/CKEditorGetImageServlet';
config.filebrowserUploadUrl = 'CKEditorUploadServlet';
//config.filebrowserUploadMethod = "form";
config.uploadUrl='CKEditorUploadServlet';
config.extraPlugins = 'image2';
};
Загрузить сервлет:
public class CKEditorUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String ERROR_FILE_UPLOAD = "An error occurred to the file upload process.";
private static final String ERROR_NO_FILE_UPLOAD = "No file is present for upload process.";
private static final String ERROR_INVALID_CALLBACK = "Invalid callback.";
private static final String CKEDITOR_CONTENT_TYPE = "text/html; charset=UTF-8";
private static final String CKEDITOR_HEADER_NAME = "Cache-Control";
private static final String CKEDITOR_HEADER_VALUE = "no-cache";
private static final Pattern PATTERN = Pattern.compile("[\\w\\d]*");
private String errorMessage = "";
public CKEditorUploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CKEDITOR_CONTENT_TYPE);
response.setHeader(CKEDITOR_HEADER_NAME, CKEDITOR_HEADER_VALUE);
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = null;
Iterator itr = null;
FileItem fi = null;
File file = null;
String contentType = "";
byte[] content;
String id = UUID.randomUUID().toString().substring(0, 8);
System.out.println(id);
final PrintWriter out = response.getWriter();
UploadBean bean = (UploadBean) getServletContext().getAttribute("uploadBean");
if (bean == null) {
bean = new UploadBean();
getServletContext().setAttribute("uploadBean", bean);
}
try {
/*final List items = upload.parseRequest(request);
if (!items.isEmpty() && items.get(0) != null) {
System.out.println("Content "+((DiskFileItem) items.get(0)).get());
System.out.println("Content Type "+((DiskFileItem) items.get(0)).getContentType());
System.out.println("Name "+((DiskFileItem) items.get(0)).getName());
} else {
//No file to Upload
}*/
fileItems = upload.parseRequest(request);
itr = fileItems.iterator();
while ( itr.hasNext () )
{
fi = (FileItem)itr.next();
if ( !fi.isFormField () )
{
String fileName = fi.getName();
System.out.println("FileName "+fileName);
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
boolean isInMemory = fi.isInMemory();
contentType = fi.getContentType();
content = fi.get();
bean.setContent(fi.get());
long sizeInBytes = fi.getSize();
if( fileName.lastIndexOf("\\") >= 0 )
{
file = new File("D:\\Document" + "\\" + id + "." + ext) ;
}
else
{
file = new File("D:\\Document\\" + "\\" + id + "." + ext) ;
}
fi.write( file ) ;
}
}
bean.setId(id);
bean.setContentType(contentType);
} catch (Exception e) {
e.printStackTrace();
}
finally
{
fileItems = null;
itr = null;
fi = null;
}
// CKEditorFuncNum Is the location to display when the callback
// String callback = request.getParameter("CKEditorFuncNum");
String callback ="1";
System.out.println("Callback "+callback);
// verify if the callback contains only digits and letters in order to
// avoid vulnerability on parsing parameter
if (!PATTERN.matcher(callback).matches()) {
System.out.println("Patten not matches");
callback = "";
errorMessage = ERROR_INVALID_CALLBACK;
}
final String pathToFile = request.getContextPath()
+ "/CKEditorGetImageServlet?imageId=" + bean.getId();
System.out.println("Path to File "+pathToFile);
out.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("
+ callback + ",'" + pathToFile + "','" + errorMessage + "')");
out.println("// ]]></script>");
out.flush();
out.close();
}
}
Сервлет GetImage
public class CKEditorGetImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String ERROR_FILE_DOWNLOAD = "An error occured when trying to get the image with id:";
private static final String IMAGE_PARAMETER_NAME = "imageId";
private static final long CACHE_AGE_MILISECONDS_TWO_WEEKS = 1209600000;
private static final String CKEDITOR_CONTENT_EXPIRE = "Expires";
private static final String CKEDITOR_CONTENT_TYPE = "Content-Type";
private static final String CKEDITOR_CONTENT_LENGTH = "Content-Length";
private static final String CKEDITOR_CONTENT_DISPOSITION = "Content-Disposition";
private static final String CKEDITOR_CONTENT_DISPOSITION_VALUE = "inline; filename=\"";
private static final String CKEDITOR_HEADER_NAME = "Cache-Control";
public CKEditorGetImageServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UploadBean bean = (UploadBean) getServletContext().getAttribute("uploadBean");
final byte[] rb = bean.getContent();
System.out.println("Inside get Image Servlet "+rb);
System.out.println("Content Type "+bean.getContentType());
final long expiry = new Date().getTime()
+ CACHE_AGE_MILISECONDS_TWO_WEEKS;
response.setDateHeader(CKEDITOR_CONTENT_EXPIRE, expiry);
response.setHeader(CKEDITOR_HEADER_NAME, "max-age="
+ CACHE_AGE_MILISECONDS_TWO_WEEKS);
response.setHeader(CKEDITOR_CONTENT_TYPE,
bean.getContentType());
response.setHeader(CKEDITOR_CONTENT_LENGTH,
String.valueOf(rb.length));
response.setHeader(
CKEDITOR_CONTENT_DISPOSITION,
CKEDITOR_CONTENT_DISPOSITION_VALUE
+ bean.getName() + "\"");
response.getOutputStream().write(rb, 0, rb.length);
response.getOutputStream().flush();
response.getOutputStream().close();
}
В соответствии с Официальной документацией ckeditor нам нужно написать код xhr на уровне редактора, а также на уровне сервера, который я не могу получить. Не могли бы вы помочь мне в достижении того же.