前一篇文章可以看到对jquery uploadify的属性的讲解,这里给出具体的java代码实现,代码基于servlet,实现了上传图片并预览的效果,不多说,上代码

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Insert title here
  
  
  
          $(function() {            $("#upload_org_code").uploadify({          'auto' :true,          'buttonClass':'mybutton',          'buttonCursor':'hand',          'buttonText'    : '选择图片',          'fileSizeLimit' : '2MB',                 'height'        : 27,                 'width'         : 80,                  'fileTypeExts'  : '*.jpg;*.jpge;*.gif;*.png',                 'fileTypeDesc'  :'请选择jpg,jpge,jif,png后缀结尾的图片',                 'progressData':'speed',                 'queueID':'some_file_queue',                 'removeCompleted':false,                 'queueSizeLimit':2,                 'removeTimeout':1,                 'swf'           : '${pageContext.request.contextPath}/scripts/uploadify.swf',                 
                 'uploader'      : '${pageContext.request.contextPath}/uploadifyServlet',                 'multi'         : false,                 //加上此句会重写onSelectError方法【需要重写的事件】                 'overrideEvents': ['onSelectError', 'onDialogClose','onCancel','onClearQueue'],                 'onCancel':function(file){                 console.log(file.name);                  },                                  'onClearQueue':function(queueItemCount){                  console.log(queueItemCount);                 },                 'onDestroy':function(){                 console.log('destory');                  },                 'onDialogClose':function(queueData){                  console.log(queueData.filesSelected );                  console.log(queueData.filesQueued  );                 },                 'onUploadSuccess':function(file,data,response){                     $('#' + file.id).find('.data').html('');                     console.log('data='+data);                     $("#upload_org_code_name").val(data);                     
                     $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/getImgServlet?file="+data);                       $("#upload_org_code_img").show();                 },                                //返回一个错误,选择文件的时候触发                 'onSelectError':function(file, errorCode, errorMsg){                     switch(errorCode) {                         case -110:                             alert("文件 ["+file.name+"] 大小超出系统限制的" + jQuery('#upload_org_code').uploadify('settings', 'fileSizeLimit') + "大小!");                             break;                         case -120:                             alert("文件 ["+file.name+"] 大小异常!");                             break;                         case -130:                             alert("文件 ["+file.name+"] 类型不正确!");                             break;                     }                 },             });                    });    
 
     
上传       
取消上传        
destory        

其中,js中定义了上传处理的uploadifyServlet地址,所以下一步就是编写改servlet了

uploadifyServlet.java

public class uploadifyServlet extends HttpServlet {		   private String configPath="d:/p_w_picpath/";	    	  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	        this.doPost(request, response);	    }	 	    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	    	  String ret_fileName = null;//返回给前端已修改的图片名称	    	  request.setCharacterEncoding("UTF-8");	          response.setContentType("text/html; charset=UTF-8");	          PrintWriter out = response.getWriter();	          // 文件保存目录路径	          String savePath = configPath; 	   	          DiskFileItemFactory factory = new DiskFileItemFactory();	          ServletFileUpload upload = new ServletFileUpload(factory);	          upload.setHeaderEncoding("UTF-8");	          try {	              List
 items = upload.parseRequest(request);               Iterator
 itr = items.iterator();                   while (itr.hasNext()) {                                   DiskFileItem item   = (DiskFileItem) itr.next();                   String fileName = item.getName();                   if(fileName!=null){                       ret_fileName  = fileName;                   }                   if (!item.isFormField()) {                    try {                           File uploadedFile = new File(savePath,fileName);                               OutputStream os = new FileOutputStream(uploadedFile);                           InputStream is = item.getInputStream();                           byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度                           int length = 0;                           while ((length = is.read(buf)) > 0) {                               os.write(buf, 0, length);                           }                           // 关闭流                           os.flush();                           os.close();                           is.close();                       } catch (Exception e) {                           e.printStackTrace();                       }                   }                                   }               } catch (FileUploadException e) {               e.printStackTrace();           }           //将已修改的图片名称返回前端           out.print(ret_fileName);           out.flush();           out.close();     }}

上述代码的意思很简单,将上传的文件放入指定的文件夹,并返回图片的名称。

到此为止,上传就结束了,下面是预览。

在onUploadSuccess中,我们得到了上传成功图片的返回的图片名称,其中我们定义了实现预览效果的后台servlet,getImgServlet

下面给出改servlet的代码

public class getImg extends HttpServlet {		   private String configPath="d:/p_w_picpath/";	    	  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	        this.doPost(request, response);	    }	 	    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	    	 String file = request.getParameter("file");	         File pic = new File(configPath+file);	  	         FileInputStream fis = new FileInputStream(pic);	         OutputStream os = response.getOutputStream();	         try {	             int count = 0;	             byte[] buffer = new byte[1024 * 1024];	             while ((count = fis.read(buffer)) != -1)	                 os.write(buffer, 0, count);	             os.flush();	         } catch (IOException e) {	             e.printStackTrace();	         } finally {	             if (os != null)	                 os.close();	             if (fis != null)	                 fis.close();	         }	          	    }}

上述代码很简单,得到传过来的文件名之后,直接发送文件流过去,实现图片显示

具体的项目包地址如下,大家可直接下载运行:

http://yun.baidu.com/share/link?shareid=702477080&uk=2836507213