Chinaunix首页 | 论坛 | 博客
  • 博客访问: 353017
  • 博文数量: 88
  • 博客积分: 1673
  • 博客等级: 上尉
  • 技术积分: 934
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-20 13:51
文章分类

全部博文(88)

文章存档

2016年(1)

2015年(4)

2014年(3)

2013年(7)

2012年(11)

2011年(1)

2009年(61)

我的朋友

分类: Java

2012-06-19 09:50:31

1.准备材料:下载jquery.uploadify上传js
 
注意:这个上传在firefox下会出现问题如果你在项目中加了拦截器,因为session会丢失,所以你可以传参的时候带上你所需要的条件,在拦截器可以不作处理这个上传的servlet,也就是判断url,跳过这个servlet的拦截,或者用其他的方法进行判定,比如根据传过来的参数判断是不是有该用户什么的,这就看自己怎么处理,
   一定要out.print(data);否则会认为上传不成功,因为前台收不到返回值,这个data可以返回你所需要的参数,然后jsp页面进行处理
           'method' : 'GET',
            'scriptData' : {'userid':'<%=userID%>'},//传参的时候网上说method要是get,这个我没有测试,用的时候自己调试一下,我这边已经成功了,需要源代码项目的可以留言+邮箱
    有些参数可以看官网上的API文档
 
2、jsp代码

点击(此处)折叠或打开

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
  2. <%@ include file="/commons/taglibs.jsp"%>
  3. <%@ taglib prefix="c" uri="" %>
  4. <%
    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
    %>
  5.    
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8.     <head>
  9.         <title>上传</title>
  10.         <meta http-equiv="pragma" content="no-cache">
  11.         <meta http-equiv="cache-control" content="no-cache">
  12.         <meta http-equiv="expires" content="0">
  13.     
  14.    
  15.     

  16.      
      
      
  17.   
  18.   
      
  19.         <script type="text/javascript">
  20.         $(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) {
  21. //后台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) {
  22. //所有上传成功的返回返回处理
        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();
          });
        }
       }
            })
     }); 

  23.             
  24.  </script>
  25. </head>
  26. <body>
  27.         

       
       
       

    仅支持jpg、png、gif格式的图片


      

  28.     </body>
  29. </html>
web.xml

点击(此处)折叠或打开

  1. <servlet>
  2.         <servlet-name>uploadCutpic</servlet-name>
  3.         <servlet-class>com.ccsuntel.linkupuser.servlet.user.UploadTmpPhotoServlet</servlet-class>
  4.     </servlet>
  5.     <servlet-mapping>
  6.         <servlet-name>uploadCutpic</servlet-name>
  7.         <url-pattern>/servlet/UploadSwfTmpPic</url-pattern>
  8.     </servlet-mapping>
servlet代码

点击(此处)折叠或打开

  1. package com.ccsuntel.linkupuser.servlet.user;

  2. import java.awt.image.BufferedImage;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;

  10. import javax.imageio.ImageIO;
  11. import javax.servlet.ServletException;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;

  15. import org.apache.commons.fileupload.FileItem;
  16. import org.apache.commons.fileupload.FileUploadException;
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;

  19. import com.ccsuntel.linkupuser.base.Config;
  20. import com.ccsuntel.linkupuser.base.Constant;
  21. import com.ccsuntel.linkupuser.base.dispatch.Base;
  22. import com.ccsuntel.linkupuser.util.Tool;
  23. import com.ccsuntel.linkupuser.util.UploadTool;

  24. public class UploadTmpPhotoServlet extends HttpServlet {

  25.     @Override
  26.     public void doGet(HttpServletRequest request, HttpServletResponse response)
  27.             throws ServletException, IOException {
  28.         
  29.     }

  30.     @Override
  31.     public void doPost(HttpServletRequest request, HttpServletResponse response)
  32.             throws ServletException, IOException {
  33.         DiskFileItemFactory factory = new DiskFileItemFactory();
  34.         // 设置内存缓冲区,超过后写入临时文件

  35.         factory.setSizeThreshold(10240000);
  36.         // 设置临时文件存储位置

  37.         String base = Config.getInstance().getWorkGtmpPath();//this.getServletContext().getRealPath("/")+"files";

  38.         File file = new File(base);
  39.         if(!file.exists())
  40.             file.mkdirs();
  41.         factory.setRepository(file);
  42.         ServletFileUpload upload = new ServletFileUpload(factory);
  43.         // 设置单个文件的最大上传值

  44.         upload.setFileSizeMax(10002400000l);
  45.         // 设置整个request的最大值

  46.         upload.setSizeMax(10002400000l);
  47.         upload.setHeaderEncoding("UTF-8");
  48.         request.setCharacterEncoding("utf-8");
  49.         response.setCharacterEncoding("utf-8");
  50.         PrintWriter out = response.getWriter();
  51.         try {
  52.             List<?> items = upload.parseRequest(request);
  53.             FileItem item = null;
  54.             String tpmFilePathName = null;
  55.             String savePath = Config.getInstance().getLinkfilesavePath();
  56.             Map<String,String> fileNames = new HashMap<String, String>();
  57.             for (int i = 0 ;i < items.size(); i++){
  58.                 item = (FileItem) items.get(i);
  59.                 // 保存文件

  60.                 if (!item.isFormField() && item.getName().length() > 0) {
  61.                     fileNames.put("oldName", item.getName());
  62.                     String suffixName = item.getName().substring(item.getName().lastIndexOf("."));
  63.                     String newName=UploadTool.createPhotoID()+suffixName;
  64.                     fileNames.put("newName", newName);
  65.                     fileNames.put("fileSize", UploadTool.FormetFileSize(item.getSize()));
  66.                     //System.out.println(item.getName()+"=="+UploadTool.createPhotoID()+suffixName+"=="+UploadTool.FormetFileSize(item.getSize())+"savePath"+savePath);

  67.                     tpmFilePathName = base + newName;//File.separator

  68.                     item.write(new File(tpmFilePathName));
  69.                     //UploadTool.removeFile(tpmFilePathName);

  70.                     BufferedImage bufImg = ImageIO.read(new File(tpmFilePathName));
  71.                     //System.out.print("======"+bufImg.getHeight()+"====="+bufImg.getWidth());
  72. //数据库操作,包图片的路径及其相应的信息保存到数据库,
  73.                     out.print(newName+"^"+bufImg.getHeight()+"^"+bufImg.getWidth());
  74.                 }
  75.             }
  76.             
  77.             
  78.             
  79.             //Map fileNames = UploadTool.WorkGroupFileUpload(request, Config.getInstance().getLinkfiletmpPath(), Config.getInstance().getLinkfilesavePath());

  80.             
  81.         } catch (FileUploadException e) {
  82.             out.print(-1);
  83.             e.printStackTrace();
  84.         } catch (Exception e) {
  85.             out.print(-1);
  86.             e.printStackTrace();
  87.         }finally{
  88.             out.flush();
  89.             out.close();
  90.         }
  91.         
  92.     }

  93. }



阅读(10602) | 评论(1) | 转发(0) |
0

上一篇:java图片裁剪原理

下一篇:Gson的应用

给主人留下些什么吧!~~