由於struts框架對request對象做了封裝,原來處理上傳圖片的upload_json.jsp文件無法使用了,於是對kindeditor中處理上傳圖片的upload_json.jsp文件進行重寫,通過多次測試後,成功實現了圖片的上傳。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
<%@ page import="org.json.simple.*"%>
<%
//文件保存目錄路徑 img_upload是服務器存儲上傳圖片的目錄名
String savePath = request.getSession().getServletContext().getRealPath("/")+ "img_upload/";
//文件保存目錄URL
String saveUrl = request.getContextPath() + "/img_upload/";
//定義允許上傳的文件擴展名
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png","bmp" };
//允許最大上傳文件大小
long maxSize = 1024000;
//Struts2 請求 包裝過濾器
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
//獲得上傳的文件名
String fileName = wrapper.getFileNames("imgFile")[0];
//獲得文件過濾器
File file = wrapper.getFiles("imgFile")[0];
//得到上傳文件的擴展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//檢查擴展名
if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
out.println(getError("上傳文件擴展名是不允許的擴展名。"));
return;
}
//檢查文件大小
if (file.length() > maxSize) {
out.println(getError("上傳文件大小超過限制。"));
return;
}
//檢查目錄
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
out.println(getError("上傳目錄不存在。"));
return;
}
//檢查目錄寫入權限
if (!uploadDir.canWrite()) {
out.println(getError("上傳目錄沒有寫入權限。"));
return;
}
//重構上傳圖片的名稱
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newImgName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;
//設置 KE 中的圖片文件地址
String newFileName = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()
+ saveUrl + newImgName;
byte[] buffer = new byte[1024];
//獲取文件輸出流
FileOutputStream fos = new FileOutputStream(savePath + newImgName);
//獲取內存中當前文件輸入流
InputStream in = new FileInputStream(file);
try {
int num = 0;
while ((num = in.read(buffer)) > 0) {
fos.write(buffer, 0, num);
}
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
in.close();
fos.close();
}
//發送給 KE
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newImgName);
out.println(obj.toJSONString());
%>
<%!private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toJSONString();
}
%>