程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> kindeditorͼƬÉÏ´« struts2ʵÏÖ

kindeditorͼƬÉÏ´« struts2ʵÏÖ

編輯:C++入門知識

kindeditorͼƬÉÏ´« struts2ʵÏÖ


Ò»¡¢kindeditorÒÔ¼°struts2²¿Êð´î½¨²»ÔÙ׸Êö,ÈçÐèÒªÇë²Î¿¼kindeditorʹÓ÷½·¨ Struts2¿ò¼Ü´î½¨

¶þ¡¢kindeditorͼƬÉÏ´«ËùÒÀÀµjar°üÔÚkindeditor\jsp\libÏÂÓÐ

Èý¡¢ÒÔÏÂÁгö²¿·ÖºËÐÄ´úÂë,ÈçÐèҪȫ²¿Ô´Âë¿Éµã»÷ÏÂÔØ(´ýÉÏ´«)


JSP

<script type="text/javascript">
   $(function(){
	KindEditor.ready(function(K) {
	       var editor1 = K.create('#editor_id', {
	        //×Ô¶¨Ò幤¾ßÀ¸
		items:[
			'code', '|', 'justifyleft', 'justifycenter', 'justifyright',
			'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent',
			'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen',
			'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
			'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat',
			'|', 'image', 'multiimage',
			'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
			'anchor', 'link', 'unlink'
		],
		uploadJson : 'ImgUpload.action', //ͼƬÉÏ´«Action
		allowImageRemote : false //È¡ÏûÍøÂçͼƬÉÏ´«
		});
	 });
   })
</script>

Struts

	
	
	

Action
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.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/";

		// Îļþ±£´æĿ¼URL
		String saveUrl = request.getContextPath() + "/attached/";

		// ¶¨ÒåÔÊÐíÉÏ´«µÄÎļþÀ©Õ¹Ãû
		HashMap extMap = new HashMap();
		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. asList(extMap.get(dirName).split(",")).contains(fileExt)) {
			out.println(getError("ÉÏ´«ÎļþÀ©Õ¹ÃûÊDz»ÔÊÐíµÄÀ©Õ¹Ãû¡£\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();
		}
		
		// ·¢Ë͸ø kindeditor
		JSONObject 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ÖеijÌÐò½øÐÐÉÏ´«Ê±Ö´Ðе½

List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {}
·¢ÏÖitrΪ¿Õ È¡²»µ½ÉÏ´«Îļþ ¹ÊûÓÐÖ´ÐÐwhileÑ­»·,Ò²¾ÍûÓзµ»ØÖµ,kindeditor±¨·þÎñÆ÷´íÎó.Ϊʲôȡ²»µ½Öµ,ÊÇÒòΪ£º

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];

Ч¹ûÈçͼ£º
þŸé¥ºÿþš[¯ø­›(h™ï饨kyÔ´Â룺ÉԵȣ¬´ýÉÏ´«


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved