1.准备材料:下载jquery.uploadify上传js
注意:这个上传在firefox下会出现问题如果你在项目中加了拦截器,因为session会丢失,所以你可以传参的时候带上你所需要的条件,在拦截器可以不作处理这个上传的servlet,也就是判断url,跳过这个servlet的拦截,或者用其他的方法进行判定,比如根据传过来的参数判断是不是有该用户什么的,这就看自己怎么处理,
一定要out.print(data);否则会认为上传不成功,因为前台收不到返回值,这个data可以返回你所需要的参数,然后jsp页面进行处理
'method' : 'GET',
'scriptData' : {'userid':'<%=userID%>'},//传参的时候网上说method要是get,这个我没有测试,用的时候自己调试一下,我这边已经成功了,需要源代码项目的可以留言+邮箱
'scriptData' : {'userid':'<%=userID%>'},//传参的时候网上说method要是get,这个我没有测试,用的时候自己调试一下,我这边已经成功了,需要源代码项目的可以留言+邮箱
有些参数可以看官网上的API文档
2、jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %> <%@ include file="/commons/taglibs.jsp"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String rootpath = request.getContextPath(); long userID = (Long)request.getSession().getAttribute("userID"); //上传url String sessionId = request.getSession().getId(); StringBuffer uploadUrl = new StringBuffer("http://"); uploadUrl.append(request.getHeader("Host")); uploadUrl.append(request.getContextPath()); uploadUrl.append("/servlet/UploadSwfTmpPic?sessionId="+sessionId); //上传url--END %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>上传</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <!-- 样式及js加载 这儿得注意引入的路径是否正确应用的时候自己多加小心--> <link href="./style/uploadify/default.css" rel="stylesheet" type="text/css" /> <link href="./style/uploadify/uploadify.css" rel="stylesheet" type="text/css" /> <script language="javascript" src="<c:url value="/scripts/jquery.js"/>"></script> <script type="text/javascript" src="./js/uploadify/swfobject.js"></script> <script type="text/javascript" src="./js/uploadify/jquery.uploadify.v2.0.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#showPic").hide(); $("#uploadify").uploadify({ 'uploader' : './js/uploadify/uploadify.swf', 'script' : '<%=uploadUrl.toString()%>',//后台处理的请求 'cancelImg' : './images/cancel.png', //每个文件后面的取消按钮 'folder' : 'uploads',//您想将文件保存到的路径 'queueID' : 'fileQueue',//与下面的id对应 'queueSizeLimit' : 50, 'fileDesc' : '文件格式(*.png;*.jpg;*.gif)', 'fileExt' : '*.png;*.jpg;*.gif', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc 'auto' : true, //是否自动提交 'multi' : false, //是否允许上传多个文件 'simUploadLimit' : 1, //允许同时上传的个数为1 'rollover' : false,//鼠标移到浏览按钮的反应 'method' : 'GET', 'scriptData' : {'userid':'<%=userID%>'}, 'buttonText' : 'BROWSE',//BROWSE 'buttonImg' : './js/uploadify/uploadify.jpg', 'hideButton' : true, 'wmode' : 'transparent', 'onComplete': function(event, queueID, fileObj,response,data) { //后台servlet一定要有返回值,否则会认为不成功,上传进度条也会不消失 if(response != -1){ $("#showPic").show(); var res = response.split("^"); path_pic = res[0]; height_y = res[1]; width_y = res[2]; $('#oimgW').html(width_y); $('#oimgH').html(height_y); urlallpic = "<%=rootpath%>/uploadfile/tmpdir/"+path_pic; }else{ alertWbox($(this), "错误提示", "头像上传失败。", 200, null, 238); } }, 'onSelect': function(e, queueId, fileObj) { //fileQueue document.getElementById("fileQueue").style.display=""; }, 'onError' : function(event, queueID, fileObj) { // alert("文件:" + fileObj.name + " 上传失败"); alertWbox($(this), "错误提示", "头像上传失败。", 200, null, 238); } , 'onAllComplete' : function(event, queueID, fileObj,response,data) { //所有上传成功的返回返回处理 if(urlallpic != "" ){ document.getElementById("fileQueue").style.display="none"; document.getElementById("showPic").style.display=""; document.getElementById("ferret").src = urlallpic; document.getElementById("minImg").src = urlallpic;// // setTimeout("readyPic();",5000); imgReady(urlallpic, function () { initcutpic(); }); } } }) }); </script> </head> <body> <div id="uploadJqFy"> <div id="fileQueue" style="display:none;"></div> <input type="file" name="uploadify" id="uploadify" /> <p>仅支持jpg、png、gif格式的图片</p> </div> </body> </html>
3.web.xml
<servlet> <servlet-name>uploadCutpic</servlet-name> <servlet-class>com.ccsuntel.linkupuser.servlet.user.UploadTmpPhotoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>uploadCutpic</servlet-name> <url-pattern>/servlet/UploadSwfTmpPic</url-pattern> </servlet-mapping>
4.servlet代码
package com.ccsuntel.linkupuser.servlet.user; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.ccsuntel.linkupuser.base.Config; import com.ccsuntel.linkupuser.base.Constant; import com.ccsuntel.linkupuser.base.dispatch.Base; import com.ccsuntel.linkupuser.util.Tool; import com.ccsuntel.linkupuser.util.UploadTool; public class UploadTmpPhotoServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存缓冲区,超过后写入临时文件 factory.setSizeThreshold(10240000); // 设置临时文件存储位置 String base = Config.getInstance().getWorkGtmpPath();//this.getServletContext().getRealPath("/")+"files"; File file = new File(base); if(!file.exists()) file.mkdirs(); factory.setRepository(file); ServletFileUpload upload = new ServletFileUpload(factory); // 设置单个文件的最大上传值 upload.setFileSizeMax(10002400000l); // 设置整个request的最大值 upload.setSizeMax(10002400000l); upload.setHeaderEncoding("UTF-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); try { List<?> items = upload.parseRequest(request); FileItem item = null; String tpmFilePathName = null; String savePath = Config.getInstance().getLinkfilesavePath(); Map<String,String> fileNames = new HashMap<String, String>(); for (int i = 0 ;i < items.size(); i++){ item = (FileItem) items.get(i); // 保存文件 if (!item.isFormField() && item.getName().length() > 0) { fileNames.put("oldName", item.getName()); String suffixName = item.getName().substring(item.getName().lastIndexOf(".")); String newName=UploadTool.createPhotoID()+suffixName; fileNames.put("newName", newName); fileNames.put("fileSize", UploadTool.FormetFileSize(item.getSize())); //System.out.println(item.getName()+"=="+UploadTool.createPhotoID()+suffixName+"=="+UploadTool.FormetFileSize(item.getSize())+"savePath"+savePath); tpmFilePathName = base + newName;//File.separator item.write(new File(tpmFilePathName)); //UploadTool.removeFile(tpmFilePathName); BufferedImage bufImg = ImageIO.read(new File(tpmFilePathName)); //System.out.print("======"+bufImg.getHeight()+"====="+bufImg.getWidth()); //数据库操作,包图片的路径及其相应的信息保存到数据库, out.print(newName+"^"+bufImg.getHeight()+"^"+bufImg.getWidth()); } } //Map<String,String> fileNames = UploadTool.WorkGroupFileUpload(request, Config.getInstance().getLinkfiletmpPath(), Config.getInstance().getLinkfilesavePath()); } catch (FileUploadException e) { out.print(-1); e.printStackTrace(); } catch (Exception e) { out.print(-1); e.printStackTrace(); }finally{ out.flush(); out.close(); } } }