kindeditor图片上传 struts2实现
生活随笔
收集整理的這篇文章主要介紹了
kindeditor图片上传 struts2实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、kindeditor以及struts2部署搭建不再贅述,如須要請參考kindeditor用法?Struts2框架搭建
二、kindeditor圖片上傳所依賴jar包在kindeditor\jsp\lib下有三、下面列出部分核心代碼,如須要所有源代碼可點擊下載
JSP
Struts
<package name="kindeditor_json" extends="json-default"><!-- 圖片上傳 --><action name="ImgUpload" class="com.home.web.ImgUploadAction" method="imgUpload"></action> </package>
Actionimport 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.PrintWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Random;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper; import org.json.simple.JSONObject;import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport;public class ImgUploadAction extends ActionSupport {private static final long serialVersionUID = 1L;public String imgUpload() {//獲取response、request對象ActionContext ac = ActionContext.getContext();HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);PrintWriter out = null; //輸出流try {out = response.getWriter();} catch (IOException e1) {e1.printStackTrace();}String savePath = ServletActionContext.getServletContext().getRealPath("/") + "attached/";// 文件保存文件夾URLString saveUrl = request.getContextPath() + "/attached/";// 定義同意上傳的文件擴展名HashMap<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp");extMap.put("flash", "swf,flv");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");// 最大文件大小long maxSize = 1000000;response.setContentType("text/html; charset=UTF-8");if (!ServletFileUpload.isMultipartContent(request)) {out.println(getError("請選擇文件。"));return null;}// 檢查文件夾File uploadDir = new File(savePath);if (!uploadDir.isDirectory()) {out.println(getError("上傳文件夾不存在。"));return null;}// 檢查文件夾寫權限if (!uploadDir.canWrite()) {out.println(getError("上傳文件夾沒有寫權限。"));return null;}String dirName = request.getParameter("dir");if (dirName == null) {dirName = "image";}if (!extMap.containsKey(dirName)) {out.println(getError("文件夾名不對。"));return null;}// 創建文件夾savePath += dirName + "/";saveUrl += dirName + "/";File saveDirFile = new File(savePath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String ymd = sdf.format(new Date());savePath += ymd + "/";saveUrl += ymd + "/";File dirFile = new File(savePath);if (!dirFile.exists()) {dirFile.mkdirs();}FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;// 獲得上傳的文件名稱String fileName = wrapper.getFileNames("imgFile")[0];// imgFile,imgFile,imgFile// 獲得文件過濾器File file = wrapper.getFiles("imgFile")[0];// 檢查擴展名String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {out.println(getError("上傳文件擴展名是不同意的擴展名。\n僅僅同意" + extMap.get(dirName)+ "格式。"));return null;}// 檢查文件大小if (file.length() > maxSize) {out.println(getError("上傳文件大小超過限制。"));return null;}// 重構上傳圖片的名稱SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");String newImgName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;byte[] buffer = new byte[1024];// 獲取文件輸出流FileOutputStream fos;// 獲取內存中當前文件輸入流InputStream in;try {fos = new FileOutputStream(savePath + "/" + newImgName);in = new FileInputStream(file);int num = 0;while ((num = in.read(buffer)) > 0) {fos.write(buffer, 0, num);}in.close();fos.close();} catch (FileNotFoundException e1) {e1.printStackTrace();} catch (IOException e) {e.printStackTrace();}// 發送給 kindeditorJSONObject obj = new JSONObject();obj.put("error", 0);obj.put("url", saveUrl + "/" + newImgName);out.println(obj.toJSONString());return null;}private String getError(String message) {JSONObject obj = new JSONObject();obj.put("error", 1);obj.put("message", message);return obj.toJSONString();} }kindeditor有自帶的jsp圖片上傳demo
uploadJson : '../jsp/upload_json.jsp'
但假設依照upload_json.jsp中的程序進行上傳時運行到
List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) {}發現itr為空 取不到上傳文件 故沒有運行while循環,也就沒有返回值,kindeditor報server錯誤.為什么取不到值,是由于:struts2過濾訪問jsp時,會改變reqeust的類型,由HttpServletRequest變成MultiPartRequestWrapper,所以parseRequest就返回了null
于是我們就須要對request進行轉換
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;這樣就能夠通過wrapper獲取上傳文件String fileName = wrapper.getFileNames("imgFile")[0]; File file = wrapper.getFiles("imgFile")[0];
效果如圖:
作者:itmyhome
源代碼:下載
總結
以上是生活随笔為你收集整理的kindeditor图片上传 struts2实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# WinForm开发系列 - Tex
- 下一篇: 用minGW编译ffmpeg(供替换op