【js】KindEditor + struts2使用詳解(上傳文件,支持多圖上傳)

KindEditor 版本  kindeditor-4.1.10

1、html

<div class="controls">
	<!-- 加載編輯器的容器 -->
	<textarea name="goodsdesc" style="width:700px; height:210px"  id="editor_id" ></textarea>
</div>

2、依賴腳本

<script type="text/javascript" charset="utf-8" src="media/kindeditor-4.1.10/kindeditor.js"></script>
    <script type="text/javascript" src="media/kindeditor-4.1.10/lang/zh-CN.js"></script>

3、下載完成後放入指定目錄,配置完成後初始化代碼

var editor;
		function InitEditor() {
			var content = '${goodsModel.goodsDesc}';
			KindEditor.ready(function(K) {
				editor = 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' ],
					//圖片上傳Action
					uploadJson : 'gfan_yyq!edit_upload.action',
					//取消網絡圖片上傳
					allowImageRemote : false,
					//添加多文件上傳
					allowFileManager : true,
					//同步數值至文本框 (爲解決js利用submit方法提交表單時無法獲取到內容)
					afterBlur: function(){this.sync();}
				});
				//編輯時加載原內容
				if(content!=null){
					editor.html(content);
				}
			});
		}
3、action

上傳至本項目

public String imgUpload() {
	    HttpServletResponse response = this.getResponse();
	    HttpServletRequest request = this.getRequest();

	    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<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();
	    }
	    // 發送給 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();
	  }

上傳值FTP

/**
	 * ftp上傳
	 * imgFileFileName 文件名
	 * imgFile 文件
	 * @return 文件地址
	 */
	private String image_upload() {
		String fname1 =  imgFileFileName.split(",")[0];
		String[] imgFullNames = { "" };
		ContinueFTP ftp = new ContinueFTP();
		try {
			//獲取配置信息
			String hostname = this.getSettingMap().get("IMG_FTP_HOSTNAME");
			String port = this.getSettingMap().get("IMG_FTP_PORT");
			String username = this.getSettingMap().get("IMG_FTP_USERNAME");
			String password = this.getSettingMap().get("IMG_FTP_PASSWORD");
			String upload_path = this.getSettingMap()
					.get("IMG_FTP_UPLOAD_PATH");
			String upload_path_virtual_directory = this.getSettingMap().get(
					"IMG_FTP_UPLOAD_PATH_VIRTUAL_DIRECTORY");
			String virtual_directory = this.getSettingMap().get(
					"IMG_FTP_VIRTUAL_DIRECTORY");
			boolean flag = ftp.connect(hostname, Integer.parseInt(port),
					username, password);
			String path = upload_path
					+ new SimpleDateFormat("yyyy/MM/dd").format(new Date())
					+ "/";
			if (flag) {
				//執行上傳
				if (imgFile != null) {
					imgFullNames[0] = path+ UUID.randomUUID().toString()+ fname1.substring(fname1.lastIndexOf('.'),fname1.length());
					ftp.upload((imgFile).getPath(), virtual_directory+ imgFullNames[0]);
					imgFullNames[0] = upload_path_virtual_directory+ imgFullNames[0];
				}
				ftp.disconnect();
			}
		} catch (Exception e) {
			return  "error";
		}
//		imgFullNames[0] = "/asdf/PImages/2016/04/07/fdf355cc-32c1-4b14-8260-4ff4f190354f.jpg";
		return imgFullNames[0];
	}

由上可知

想要獲取到文件有兩種辦法

/**
	     * 第一種 利用wrapper對象
	     */
	    MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
	    // 獲得上傳的文件名
	    String fileName = wrapper.getFileNames("imgFile")[0];// imgFile,imgFile,imgFile
	    // 獲得文件過濾器
	    File file = wrapper.getFiles("imgFile")[0];

	    /**
	     * 第二種 利用struts2特性(生成get,set方法)
	     */
	    private String imgFileFileName;
		private File imgFile;
		
		public String getImgFileFileName() {
			return imgFileFileName;
		}

		public void setImgFileFileName(String imgFileFileName) {
			this.imgFileFileName = imgFileFileName;
		}

		public void setImgFile(File imgFile) {
			this.imgFile = imgFile;
		}

		public File getImgFile() {
			return imgFile;
		}

4、注意,多圖上傳不兼容火狐瀏覽器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章