JFinal+CKEditor文件上传后缀验证,大小验证。

public void index(){
		String extName = "";// 扩展名
		String fileName = "";// 文件名
		String newFileName = "";// 新文件名
		
		try {
			String strPath = JFinal.me().getServletContext().getRealPath("/upload/news/");
			UploadFile upload = getFile("bigPic", strPath, 2097152);
                        String uploadFileName = upload.getFileName();

                        String CKEditorFuncNum = getPara("CKEditorFuncNum");
			
			// 获取扩展名
			if (uploadFileName.lastIndexOf(".") > -1) {
				extName = getExtention(upload.getFileName());
				fileName = uploadFileName.substring(0,uploadFileName.lastIndexOf("."));
			}
			newFileName = fileName+"-"+Tools.getFileName() + extName;
			if (!".jpg.gif.png,bmp.JPG.GIF.PNG.BMP".contains(extName)) {
				FileKit.delete(upload.getFile());
				renderHtml("<script type=\"text/javascript\">alert(\"请上传图片文件。\");</script>");
			} else {
				File f = upload.getFile();
				
				InputStream is = new FileInputStream(f);
				OutputStream os = new FileOutputStream(new File(strPath + File.separator + newFileName));
				try {
					byte[] buffer = new byte[1024 * 1024];
					while (is.read(buffer) > 0) {
						os.write(buffer);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (is != null) {
						is.close();
					}
					if (os != null) {
						os.close();
					}
				}
				// 删除原文件
				FileKit.delete(upload.getFile());
				// 返回给ckeditor
				renderHtml("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction("
									+ CKEditorFuncNum + ", '"+getBasePath(getRequest())+"upload/news/" + newFileName + "', '');</script>");
			}
		}catch (RuntimeException e) {
			// TODO: handle exception
			renderHtml("<script type=\"text/javascript\">alert(\"上传的文件有误,请重新上传。\");javascript:history.go(-1);</script>");
		} catch (Exception e) {
			e.printStackTrace();
			renderHtml("<script type=\"text/javascript\">alert(\"上传文件失败,请联系管理员。\");</script>");
		}
	}



你可能感兴趣的:(上传,jFinal)