Easyui上传图片功能

    首先说到easyui,在完成一个easyui的项目的时候,被这个上传图片这一步折腾了很久,我写这个博客就是为了以后不会的时候可以再次看看,好熟悉起来,我这个是用实体类做的项目,下面就展示上传图片的相关代码。

做这个项目是用到了自己写的mvc框架

在servlet里写一个上传图片的方法 到时候页面那边需要调用这个方法 开始SmartUpload要有一个夹包然后进行图片那些设置 里面写到了要先有一个添加图片名字属性那些的方法  然后再有一个根据id修改当前图片地址的方法

/**
	 * 书籍上传图片
	 * 
	 * @param req
	 * @param resp
	 * @param servletConfig
	 * @return
	 */
	public String imageUpload(HttpServletRequest req, HttpServletResponse resp, ServletConfig servletConfig) {
		SmartUpload su = new SmartUpload();
		try {//下面是设置属性
			su.initialize(servletConfig, req, resp);
			su.setCharset("utf-8");
			su.upload();
			su.setAllowedFilesList("jpg,png,gif,jpeg");
			su.setDeniedFilesList("jsp,java,html,doc");
			su.setMaxFileSize(1024 * 1024 * 800);
			String book = req.getParameter("book_id");
			File file = su.getFiles().getFile(0);
			String path = "imgs/";
			if (!file.isMissing()) {
				file.setCharset("utf-8");
				path += file.getFileName();
				file.saveAs(path, File.SAVEAS_VIRTUAL);
			}
			//然后设置图片表里面的值调用添加方法 等于添加一个图片进去
			Doc doc = new Doc();
			String file_name = path.substring(path.indexOf("/")+1, path.lastIndexOf("."));
			String mime = path.substring(path.lastIndexOf("."));
			Random r = new Random();
			int image_id = r.nextInt(1000)+1000;
			doc.setId(image_id);
			doc.setFile_name((file_name+mime).toString().trim());
			doc.setMime(mime);
			int update = 0;
			update = docdao.addDoc(doc);// 在图片表添加当前图片!
			if (update > 0) {//如果大于0 就是有值
				Book book2 = new Book();
				book2.setBook_image(image_id);
				book2.setBook_id(Integer.valueOf(book));
				int u = bookdao.imageUpload(book2);// 调用根据id修改当前书籍的图片地址!
				if (u > 0) {// 如果成功的话,就到XX页面去
					return "success";
				}
			} else {
				return "failed";
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {。。。。异常
最后返回  return "failed";

这是在mvc框架里的代码

package com.mvc.framework;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class Action {

	protected abstract String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException;

	protected abstract String execute(HttpServletRequest req, HttpServletResponse resp, ServletConfig servletConfig)
			throws ServletException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException;
}
//上面是Action类里代码



//这里是中央控制器的代码
public class ActionServlet extends HttpServlet {

	private ConfigModel configModel;

	@Override
	public void init() throws ServletException {
		try {
			String xmlPath = this.getInitParameter("aaa");
			if (xmlPath == null && "".equals(xmlPath)) {
				configModel = ConfigModelFactory.bulidConfig();
			} else {
				configModel = ConfigModelFactory.bulidConfig(xmlPath);
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("can not find configModle");
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String url = req.getServletPath();// 请求名
		url = url.substring(0, url.lastIndexOf("."));
		// Action action = map.get(url);
		if (configModel != null) {
			ActionModel actionModle = configModel.getaction(url);// 拿到action的path
			if (actionModle != null) {
				String type = actionModle.getType();// 通过path得到action的全路径名
				try {
					Action action = (Action) Class.forName(type).newInstance();// action获得全路径名初始化
					if (action instanceof ModelDriver) {
						ModelDriver modelDriver = (ModelDriver) action;
						Object model = modelDriver.getModel(req);
						BeanUtils.populate(model, req.getParameterMap());
					}
					String execute = action.execute(req, resp, this.getServletConfig());//这里传了一个this.getServletConfig() 上传图片用到了
					ForwardModel forwardModer = actionModle.getForwardModer(execute);// 拿到forward的name
					if (forwardModer != null) {
						if (forwardModer.isRedirect()) {
							resp.sendRedirect(forwardModer.getPath());
						} else {
							req.getRequestDispatcher(forwardModer.getPath()).forward(req, resp);
						}
					} else {
						throw new RuntimeException("can not find forwardModer");
					}
				} catch (InstantiationException e) {
					// TODO Auto-generated catch bl。。



//这里是继承Action的类扩展action里方法
package com.mvc.framework;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ActionSupport extends Action{

	@Override
	protected String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		String methodName = req.getParameter("methodName");
	//	if(methodName==null && "".equals(methodName)) {
			Map<String, String[]> map = req.getParameterMap();
			Set<Entry<String, String[]>> entrySet = map.entrySet();
			for (Entry<String, String[]> entry : entrySet) {
				String key = entry.getKey();
				if(key.contains("method:")) {
					methodName=key.replace("method:","");
				}
			}
	//	}
		Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
		method.setAccessible(true);
		return (String) method.invoke(this,req,resp);	
	}

	
//后面这个用到上传图片
	@Override
	protected String execute(HttpServletRequest req, HttpServletResponse resp, ServletConfig servletConfig)
			throws ServletException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		String methodName = req.getParameter("methodName");
		Map<String, String[]> map = req.getParameterMap();
		Set<Entry<String, String[]>> entrySet = map.entrySet();
		for (Entry<String, String[]> entry : entrySet) {
			String key = entry.getKey();
			if (key.contains("method:")) {
				methodName = key.replace("method:", "");
			}
		}
		Method method = null;
		try {
			method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.setAccessible(true);
			return (String) method.invoke(this, req, resp);
		} catch (NoSuchMethodException e) {
			method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class, ServletConfig.class);
			method.setAccessible(true);
			return (String) method.invoke(this, req, resp, servletConfig);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}

现在是jsp页面写一个上传图片的input

	<form enctype="multipart/form-data"
			action="ddd" id="imageUpload" method="post">
				&nbsp;&nbsp;选择图片:<input id="idFile" style="width: 224px" runat="server" name="pic"
					onchange="javascript:setImagePreview(this,localImag,preview);"
					type="file" /> <br> <br> <br> &nbsp;&nbsp;<input
					type="button" value="确定" id="image_update" onclick="imageUu()"><!-- 点击它去掉用那个方法 -->
			</form>

//在js页面
  toolbar: [{//点击这个toolbar
			iconCls: 'icon-add',
			text:'上传图片',
			handler: function(){
				var row= $('#dg').datagrid("getSelected");//拿到这个datagrid选中的那一行
				if(row){
					$("#dc").dialog('open');//打开dialog框
				}else{
					alert('请选择一本书');
				}
			}
	}

function imageUu() {//这里就是开始拿到id调用方法完成提交form表单
	var row=$('#dg').datagrid("getSelected");//拿到这个datagrid选中的那一行
	var book_id = row.book_id;//拿到书本id
	//form表单action提交调用那个上传图片方法拼接上id
	$("#imageUpload").attr("action", $("#URL").val() +"/bookservlet.action?methodName=imageUpload&&book_id="+book_id);
	$("#imageUpload").submit();//拿到form的id进行提交
}

上面代码都写好之后进行可进行上传图片了 然后就ok 了 记得多刷新刷新试试 反复测试  才可保证有没有错误哦!

猜你喜欢

转载自blog.csdn.net/qq_43227109/article/details/82990431