需要jsmartcom_zh_CN.jar支持. 下载地址: http://files.cnblogs.com/simpledev/jsmartcom_zh_CN.rar
<%@page import="com.bn.car.core.Constants"%> <%@ page contentType="text/html;charset=UTF-8" language="java" import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%> <% String pageSource = request.getParameter("pageSource"); //定义接收的源页面,可以将该图片上传工具类独立抽象出来放入include文件夹中。 SmartUpload mySmartUpload = new SmartUpload(); long file_size_max = 4000000; String fileName2 = "", ext = "", testvar = ""; String url = ""; if(pageSource == "addparts" || pageSource.equals("addparts")){ url = Constants.PARTSPATH; //常量类定义上传目录 }else if(pageSource == "addcar2" || pageSource.equals("addcar2")){ url = Constants.CARPATH; //常量类定义上传目录 } //初始化 mySmartUpload.initialize(pageContext); //只允许上载此类文件 try { mySmartUpload.setAllowedFilesList("jpg,gif");//此处的文件格式可以根据需要自己修改 //上载文件 mySmartUpload.upload(); } catch (Exception e) { %> <SCRIPT language=javascript> alert("只允许上传.jpg和.gif类型图片文件"); </script> <% } try { com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0); if (myFile.isMissing()) { %> <SCRIPT language=javascript> alert("请先选择要上传的文件"); </script> <% } else { ext = myFile.getFileExt(); //取得后缀名 int file_size = myFile.getSize(); //取得文件的大小 String saveurl = ""; if (file_size < file_size_max) { //更改文件名,取得当前上传时间的毫秒数值 Calendar calendar = Calendar.getInstance(); String filename = String.valueOf(calendar.getTimeInMillis()); //图片上传地址 saveurl = Constants.ROOTPATH + url; String pic_url = filename + "." + ext; //文件名+后缀 saveurl += pic_url; //保存路径 myFile.saveAs(saveurl, SmartUpload.SAVE_PHYSICAL); String ret = "alert('上传成功!');"; out.print("<script language=javascript>" + ret + "</script>"); //将新上传的图片放入到session中. String picUrls = (String)session.getAttribute(pageSource + "_picUrls"); if(picUrls == null){ session.setAttribute(pageSource + "_picUrls",pic_url); }else{ picUrls = pic_url + "," + picUrls; //以逗号分割. 新上传的在前面 session.setAttribute(pageSource + "_picUrls",picUrls); } //转发,根据原来的页面判断去向。 if(pageSource == "addparts" || pageSource.equals("addparts")){ response.sendRedirect("../supply/addparts.jsp"); }else if(pageSource == "addcar2" || pageSource.equals("addcar2")){ response.sendRedirect("../caruser/addcar2.jsp"); } } } } catch (Exception e) { e.printStackTrace(); out.print(e.toString()); } %>