1. 程式人生 > >CKEditor圖片上傳實現詳細步驟(使用Struts 2)

CKEditor圖片上傳實現詳細步驟(使用Struts 2)

struts2 none bject parameter found contains 使用 工具 call

本人使用的CKEditor版本是4.7.0

CKEditor的編輯器工具欄中有一項“圖片域”,該工具可以貼上圖片地址來在文本編輯器中加入圖片,但是沒有圖片上傳。

“預覽”中有一大堆鳥語,看得很不爽。可以打開ckeditor/plugins/image/dialogs/image.js文件,搜索"b.config.image_previewText"就能找到這段鳥語了,(b.config.image_previewText||‘‘)單引號中的內容全刪了。

下面研究圖片上傳。

step 1:

首先,還是image.js這個文件,搜索“upload”可以找到這一段

id:‘Upload‘,hidden:

實際上上傳功能被隱藏了,把上面的true改成false,再打開編輯器,就能找到上傳功能了。

step 2:

上面的只是一個上傳頁面。也就相當於一個HTML的form表單,要配置點擊“上傳到服務器上”按鈕後請求的Action。可以在ckeditor/config.js中配置。

加入:

config.filebrowserUploadUrl="actions/ckeditorUpload";

"ckeditorUpload"是請求的URL,也就是點擊這個按鈕就會post到ckeditorUpload地址進行處理,這裏指向的是Struts 2的一個Action

<package name="actions" extends
="struts-default" namespace="/actions"> <action name="ckeditorUpload" class="com.xxx.CkeditorUpload "> </action> </package>

step 3:

文件上傳的控件相當於<input type="file" name="upload" .../>,其name是”upload”,知道了name那麽就可以在Action中獲取這個文件。

private File upload;  //文件  
private String uploadContentType;  //
文件類型 private String uploadFileName; //文件名

以上三個私有變量都要有set方法。如果不了解的話可以先學習一下Struts 2文件上傳。

step 4:

如果上傳的圖片格式不正確,可以在上傳界面進行提示。

技術分享圖片

這個提示不是ckeditor提示的,要在Action中響應。

String callback = ServletActionContext.getRequest().getParameter("CKEditorFuncNum");   
if([判斷條件]){  
    out.println("<script type=\"text/javascript\">");    
    out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",‘‘," + "‘文件格式不正確(必須為.jpg/.gif/.bmp/.png文件)‘);");   
    out.println("</script>");  
    return null;  
}  

step 5:

這段代碼是Struts 2上傳圖片的核心代碼,把圖片上傳後保存在項目的某個目錄下,並隨機重命名。

step 6:

圖片上傳成功,在目錄下也可以看到圖片,至此圖片上傳成功。但是如何將圖片發到編輯器中呢?

點“確定”按鈕會有以下提示。

技術分享圖片

到這裏,要在Action中返回一段JS腳本。

有了這段代碼,圖片上傳成功後,根據這裏的

"img/postImg/" + filename

相對地址,就可以使用這個圖片,直接轉到“圖像”頁面。

技術分享圖片

附:Struts 2 Action代碼

技術分享圖片
package com.nos.java.action.teacher;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.hibernate.Page;


import com.nos.base.action.BaseAction;
import com.nos.base.pojo.MyVisit;
import com.nos.base.pojo.UserVo;
import com.nos.commons.util.ConstComm;
import com.nos.commons.util.InterFaceConstComm;
import com.nos.commons.util.LoggerUtils;
import com.nos.commons.util.PubTool;
import com.nos.commons.util.ResolveXml;
import com.nos.java.action.downl.IcpInformatAction;
import com.nos.java.pojo.Pro;
import com.nos.java.pojo.ProModule;
import com.nos.java.pojo.Task;
import com.nos.java.service.icp.IProModuleService;
import com.nos.java.service.icp.IProService;
import com.nos.java.service.icp.ISystemConfigService;
import com.nos.java.service.icp.ITaskService;
import com.nos.java.utils.WriteUtils;
import com.nos.java.vo.CompanyVo;
import com.nos.java.vo.ZtreeVo;
@SuppressWarnings("serial")
@Results({
@Result(name = "list", location = "task_list.jsp"),
@Result(name = "edit", location = "task_edit.jsp")
})
public class TaskManagerAction extends BaseAction{
private File upload;  //文件  
private String uploadContentType;  //文件類型  
private String uploadFileName;   //文件名 

// private String imgeArray [] = {".bmp", ".gif", ".jpe", ".jpeg", ".jpg", ".png"}; 
private static List<String> imgList = new ArrayList<>();
static{
imgList.add(".bmp");
imgList.add(".gif");
imgList.add(".jpe");
imgList.add(".jpeg");
imgList.add(".jpg");
imgList.add(".png");
}
public void uploadImg() throws IOException{

String postfix = uploadFileName.substring(uploadFileName.lastIndexOf("."));

boolean flag = imgList.contains(postfix);

System.out.println(flag);

HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
response.setContentType("text/html;charset=utf-8");
// ServletOutputStream out = response.getOutputStream();
PrintWriter out = response.getWriter();
String callback =ServletActionContext.getRequest().getParameter("CKEditorFuncNum"); 

if(!flag){
out.println("<script type=\"text/javascript\">"); 
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback  
                    + ",‘ ‘," + "‘文件格式不正確(必須為.jpg/.gif/.bmp/.png/.jpe/.png文件)‘);");  
//            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback  
//                    + ",‘ ‘," + "‘\u6587\u4ef6\u683c\u5f0f\u4e0d\u6b63\u786e\uff08\u5fc5\u987b\u4e3a\u002e\u006a\u0070\u0067\u002f\u002e\u0067\u0069\u0066\u002f\u002e\u0062\u006d\u0070\u002f\u002e\u0070\u006e\u0067\u6587\u4ef6\uff09‘);");  
            out.println("</script>");
return;
}


//按時間保存圖片
Calendar calendar = Calendar.getInstance();

int year = calendar.get(Calendar.YEAR);

int month = calendar.get(Calendar.MONTH) + 1;

int day = calendar.get(Calendar.DAY_OF_MONTH);

//獲取保存時間
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uploadDate = sdf.format(new Date());

String uploadPath = ServletActionContext.getServletContext().getRealPath("/uploadImages") + "\\" + year;
//      + "\\" + month + "\\" + day;    //取得真實路徑  

if(month < 10){
uploadPath = uploadPath + "\\0" + month;
}else {
uploadPath = uploadPath + "\\" + month;
}

if(day < 10){
uploadPath = uploadPath + "\\0" + day;
}else {
uploadPath = uploadPath + "\\" + day;
}

File relPath = new File(uploadPath);

if(!relPath.exists()){
relPath.mkdirs();
}

File saveFilePath = new File(relPath,new Date().getTime() + postfix);

String imagePath = saveFilePath.getPath();

int index = imagePath.indexOf("uploadImages");

imagePath = imagePath.substring(index);

InputStream is = new FileInputStream(upload);
OutputStream os = new FileOutputStream(saveFilePath);

byte[] buffer = new byte[1024];     
int length = 0;  
while ((length = is.read(buffer)) > 0) {     
   os.write(buffer, 0, length);     
}     
is.close();  
os.close(); 

// String projectName = request.getContextPath();
imagePath = request.getScheme()+"://"+request.getLocalAddr()+":"+request.getServerPort()+request.getContextPath()+"/"+imagePath;
// imagePath = (imagePath).replaceAll("\\\\", "\\\\\\\\");
imagePath = (imagePath).replaceAll("\\\\", "/");
out.println("<script type=\"text/javascript\">");  
out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",‘" +imagePath + "‘,‘‘)");   
out.println("</script>");
}
}
View Code

CKEditor圖片上傳實現詳細步驟(使用Struts 2)