ajaxfileupload的使用实例

http://blog.csdn.net/sidongxue2/article/details/43952191

今天简单总结一下ajaxfileupload的用法,具体实例如下:

1.上传一个文件并携带多个参数.
2.上传多个文件并携带多个参数.
  扩展:可以通过jquery扩展为添加文件选择框,去除文件选择框,而不是写死只能上传几个文件.
3.上传一个文件并携带多个参数,同时上传完成之后,及时显示.
4.上传一个文件并携带多个参数,上传之前实现预览.

5.上传一个文件,并携带多个参数. 

   通过css将界面完善的更加人性化:点击图片选择文件.

项目通过maven构建,前后台通过springmvc交互数据,spring采用注解方式.

a.闲话少说先看web.xml文件,如下:

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <display-name>message-web</display-name>    
  8.       
  9.     <!-- 配置log4j配置文件和监听器 -->   
  10.     <context-param>  
  11.             <param-name>log4jConfigLocation</param-name>  
  12.             <param-value>classpath:log4j.properties</param-value>  
  13.     </context-param>  
  14.     <listener>  
  15.        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  16.     </listener>  
  17.       
  18.     <!-- 配置springmvc主控servlet -->  
  19.     <servlet>  
  20.         <servlet-name>springmvc</servlet-name>  
  21.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  22.         <init-param>  
  23.             <param-name>contextConfigLocation</param-name>  
  24.             <param-value>classpath:springmvc.xml</param-value>  
  25.         </init-param>  
  26.     </servlet>  
  27.     <servlet-mapping>  
  28.         <servlet-name>springmvc</servlet-name>  
  29.         <url-pattern>*.mvc</url-pattern>  
  30.     </servlet-mapping>  
  31.       
  32.     <!-- 添加字符集过滤器 -->  
  33.     <filter>  
  34.         <filter-name>encodingFilter</filter-name>  
  35.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  36.         <init-param>  
  37.             <param-name>encoding</param-name>  
  38.             <param-value>UTF-8</param-value>  
  39.         </init-param>  
  40.     </filter>  
  41.     <filter-mapping>  
  42.         <filter-name>encodingFilter</filter-name>  
  43.         <url-pattern>/*</url-pattern>  
  44.     </filter-mapping>  
  45. </web-app>  
b.接着看spring配置文件和log4j配置文件,

[html]  view plain copy
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans     
  5.         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
  6.         http://www.springframework.org/schema/context     
  7.         http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
  8.   
  9.     <!-- 配置controller扫描 -->  
  10.     <context:component-scan base-package="com.ilucky.ajaxfileupload" />  
  11.   
  12.     <!-- 设置上传文件的最大尺寸为100MB -->  
  13.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  14.         <property name="maxUploadSize">  
  15.             <value>102400000</value>  
  16.         </property>  
  17.     </bean>  
  18. </beans>    
[html]  view plain copy
  1. #Loggers  
  2. log4j.rootLogger=debug,console,file  
  3.   
  4. #console  
  5. log4j.appender.console=org.apache.log4j.ConsoleAppender  
  6. log4j.appender.console.Threshold = DEBUG  
  7. log4j.appender.console.layout=org.apache.log4j.PatternLayout  
  8. log4j.appender.console.layout.ConversionPattern=[%d]-%p-%l-%m%n  
  9.   
  10. #file  
  11. log4j.appender.file=org.apache.log4j.RollingFileAppender  
  12. log4j.appender.file.Append = true  
  13. log4j.appender.file.Threshold = DEBUG  
  14. log4j.appender.file.ImmediateFlush = true  
  15. log4j.appender.file.File=../webapps/ajaxfileupload.log  
  16. log4j.appender.file.MaxFileSize=2500KB  
  17. log4j.appender.file.MaxBackupIndex=20  
  18. log4j.appender.file.layout=org.apache.log4j.PatternLayout  
  19. log4j.appender.file.layout.ConversionPattern=[%d]-%p-%l-%m%n  
c.然后看控制类.

[java]  view plain copy
  1. package com.ilucky.ajaxfileupload;  
  2.   
  3. import java.io.File;  
  4. import java.io.PrintWriter;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.apache.log4j.Logger;  
  12. import org.springframework.context.annotation.Scope;  
  13. import org.springframework.stereotype.Controller;  
  14. import org.springframework.web.bind.annotation.RequestMapping;  
  15. import org.springframework.web.bind.annotation.RequestParam;  
  16. import org.springframework.web.multipart.MultipartFile;  
  17.   
  18. import com.alibaba.fastjson.JSON;  
  19.   
  20. /** 
  21.  * 注意: 
  22.  * 1.如果从前台传到后台的数据出现中文乱码,在web.xml文件中配置字符集过滤器. 
  23.  * 2.如果从后台传到前台的数据出现中文乱码,为response设置编码方式. 
  24.  * @author IluckySi 
  25.  * @since 20150213 
  26.  */  
  27. @Controller("uploadFileController")  
  28. @Scope("prototype")  
  29. @RequestMapping("/uploadFileController")  
  30. public class UploadFileController {  
  31.   
  32.     private static Logger logger = Logger.getLogger(UploadFileController.class);  
  33.       
  34.     @RequestMapping("/ajaxfileupload")  
  35.     public void ajaxfileupload(HttpServletRequest request, HttpServletResponse response,  
  36.             @RequestParam(value = "username", required = true) String username,  
  37.             @RequestParam(value = "password", required = true) String password,  
  38.             @RequestParam(value = "photo", required = true) MultipartFile photo) {  
  39.           
  40.         logger.info("后台收到参数: username = " + username + ", password = " + password +  
  41.                 ", photo = " + photo.getOriginalFilename());  
  42.         response.setCharacterEncoding("utf-8");  
  43.         PrintWriter pw = null;  
  44.         Map<String, String> result = new HashMap<String, String>();  
  45.         String imagePath = request.getSession().getServletContext().getRealPath("/");  
  46.         String imageName = "image/" + photo.getOriginalFilename().replace(" """);  
  47.         try {  
  48.             /** 
  49.              * 模拟位置1:前台error方法. 
  50.              * 模拟代码:int j = 2/0; 
  51.              */  
  52.             pw = response.getWriter();  
  53.             /** 
  54.              * 模拟位置2:前台success方法. 
  55.              * 模拟代码:int j = 2/0; 
  56.              */  
  57.             if(photo.getSize() > 0) {  
  58.                 photo.transferTo(new File(imagePath + imageName));  
  59.                 logger.info("存储图片成功: " + photo.getOriginalFilename());  
  60.             }  
  61.             result.put("result""success");  
  62.             result.put("message""存储图片成功!");  
  63.         } catch (Exception e) {  
  64.             logger.error("存储图片失败:" + e);  
  65.             result.put("result""failure");  
  66.             result.put("message""存储图片失败!");  
  67.         } finally {  
  68.             pw.print(JSON.toJSONString(result));  
  69.         }  
  70.     }  
  71.       
  72.     @RequestMapping("/ajaxfileupload2")  
  73.     public void ajaxfileupload2(HttpServletRequest request, HttpServletResponse response,  
  74.             @RequestParam(value = "username", required = true) String username,  
  75.             @RequestParam(value = "password", required = true) String password,  
  76.             @RequestParam(value = "photo", required = true) MultipartFile[] photo) {  
  77.           
  78.         logger.info("后台收到参数: username = " + username + ", password = " + password +  
  79.                 ", photo = " + photo.length);  
  80.         response.setCharacterEncoding("utf-8");  
  81.         PrintWriter pw = null;  
  82.         Map<String, String> result = new HashMap<String, String>();  
  83.         String imagePath = request.getSession().getServletContext().getRealPath("/");  
  84.         try {  
  85.             pw = response.getWriter();  
  86.             for(int i = 0; i < photo.length; i++) {  
  87.                 MultipartFile p = photo[i];  
  88.                 if(p.getSize() > 0) {  
  89.                     String imageName = "image/" + p.getOriginalFilename().replace(" """);  
  90.                     p.transferTo(new File(imagePath + imageName));  
  91.                     logger.info("存储图片成功: " + p.getOriginalFilename());  
  92.                 }  
  93.             }  
  94.             result.put("result""success");  
  95.             result.put("message""存储图片成功!");  
  96.         } catch (Exception e) {  
  97.             logger.error("存储图片失败:" + e);  
  98.             result.put("result""failure");  
  99.             result.put("message""存储图片失败!");  
  100.         } finally {  
  101.             pw.print(JSON.toJSONString(result));  
  102.         }  
  103.     }  
  104.       
  105.     @RequestMapping("/ajaxfileupload3")  
  106.     public void ajaxfileupload3(HttpServletRequest request, HttpServletResponse response,  
  107.             @RequestParam(value = "username", required = true) String username,  
  108.             @RequestParam(value = "password", required = true) String password,  
  109.             @RequestParam(value = "photo", required = true) MultipartFile photo) {  
  110.           
  111.         logger.info("后台收到参数: username = " + username + ", password = " + password +  
  112.                 ", photo = " + photo.getOriginalFilename());  
  113.         response.setCharacterEncoding("utf-8");  
  114.         PrintWriter pw = null;  
  115.         Map<String, String> result = new HashMap<String, String>();  
  116.         String imagePath = request.getSession().getServletContext().getRealPath("/");  
  117.         String imageName = "image/" + photo.getOriginalFilename().replace(" """);  
  118.         try {  
  119.             pw = response.getWriter();  
  120.             if(photo.getSize() > 0) {  
  121.                 photo.transferTo(new File(imagePath + imageName));  
  122.                 logger.info("存储图片成功: " + photo.getOriginalFilename());  
  123.             }  
  124.             result.put("result""success");  
  125.             result.put("message", imageName);  
  126.         } catch (Exception e) {  
  127.             logger.error("存储图片失败:" + e);  
  128.             result.put("result""failure");  
  129.             result.put("message""存储图片失败!");  
  130.         } finally {  
  131.             pw.print(JSON.toJSONString(result));  
  132.         }  
  133.     }  
  134.       
  135.     @RequestMapping("/ajaxfileupload4")  
  136.     public void ajaxfileupload4(HttpServletRequest request, HttpServletResponse response,  
  137.             @RequestParam(value = "username", required = true) String username,  
  138.             @RequestParam(value = "password", required = true) String password,  
  139.             @RequestParam(value = "photo", required = true) MultipartFile photo) {  
  140.           
  141.         logger.info("后台收到参数: username = " + username + ", password = " + password +  
  142.                 ", photo = " + photo.getOriginalFilename());  
  143.         response.setCharacterEncoding("utf-8");  
  144.         PrintWriter pw = null;  
  145.         Map<String, String> result = new HashMap<String, String>();  
  146.         String imagePath = request.getSession().getServletContext().getRealPath("/");  
  147.         String imageName = "image/" + photo.getOriginalFilename().replace(" """);  
  148.         try {  
  149.             pw = response.getWriter();  
  150.             if(photo.getSize() > 0) {  
  151.                 photo.transferTo(new File(imagePath + imageName));  
  152.                 logger.info("存储图片成功: " + photo.getOriginalFilename());  
  153.             }  
  154.             result.put("result""success");  
  155.             result.put("message""存储图片成功!");  
  156.         } catch (Exception e) {  
  157.             logger.error("存储图片失败:" + e);  
  158.             result.put("result""failure");  
  159.             result.put("message""存储图片失败!");  
  160.         } finally {  
  161.             pw.print(JSON.toJSONString(result));  
  162.         }  
  163.     }  
  164.       
  165.     @RequestMapping("/ajaxfileupload5")  
  166.     public void ajaxfileupload5(HttpServletRequest request, HttpServletResponse response,  
  167.             @RequestParam(value = "username", required = true) String username,  
  168.             @RequestParam(value = "password", required = true) String password,  
  169.             @RequestParam(value = "photo", required = true) MultipartFile photo) {  
  170.           
  171.         logger.info("后台收到参数: username = " + username + ", password = " + password +  
  172.                 ", photo = " + photo.getOriginalFilename());  
  173.         response.setCharacterEncoding("utf-8");  
  174.         PrintWriter pw = null;  
  175.         Map<String, String> result = new HashMap<String, String>();  
  176.         String imagePath = request.getSession().getServletContext().getRealPath("/");  
  177.         String imageName = "image/" + photo.getOriginalFilename().replace(" """);  
  178.         try {  
  179.             pw = response.getWriter();  
  180.             if(photo.getSize() > 0) {  
  181.                 photo.transferTo(new File(imagePath + imageName));  
  182.                 logger.info("存储图片成功: " + photo.getOriginalFilename());  
  183.             }  
  184.             result.put("result""success");  
  185.             result.put("message""存储图片成功!");  
  186.         } catch (Exception e) {  
  187.             logger.error("存储图片失败:" + e);  
  188.             result.put("result""failure");  
  189.             result.put("message""存储图片失败!");  
  190.         } finally {  
  191.             pw.print(JSON.toJSONString(result));  
  192.         }  
  193.     }  
  194. }  
d.依次看5个实例.

[html]  view plain copy
  1. <!--   
  2. 上传一个文件并携带多个参数.  
  3.  @author IluckySi  
  4.  @since 20150213  
  5.  -->  
  6. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  7. <%  
  8. String path = request.getContextPath();  
  9. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  10. %>  
  11. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  12. <html>  
  13.   <head>  
  14.      <base href="<%=basePath%>">  
  15.     <title>test</title>  
  16.     <meta http-equiv="pragma" content="no-cache">  
  17.     <meta http-equiv="cache-control" content="no-cache">  
  18.     <meta http-equiv="expires" content="0">      
  19.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.     <meta http-equiv="description" content="This is my page">  
  21.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  22.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  23.     <script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>  
  24.     <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>  
  25.     <script>  
  26.     var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload.mvc';  
  27.     $(function(){  
  28.         $('#upload').click(function(e){  
  29.             var username = $('#username').val();  
  30.             var password = $('#password').val();  
  31.             var isValidate = false;  
  32.             if(username == '' || password == '') {  
  33.                   $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');  
  34.             } else {  
  35.                 isValidate = true;  
  36.             }  
  37.             if(isValidate) {  
  38.                 $.ajaxFileUpload({  
  39.                     url:uploadUrl,  
  40.                     secureuri:false,  
  41.                     //文件选择框的id属性.  
  42.                     fileElementId:'photo',  
  43.                     dataType: 'json',  
  44.                     data:{  
  45.                         username:username,  
  46.                         password:password     
  47.                     },   
  48.                     //注意:这里的success方法代表的是前台成功接收了后台返回的数据.  
  49.                     success: function (data, status) {  
  50.                         if(data.result == 'success') {  
  51.                             alert(data.message);  
  52.                             //继续成功的逻辑...  
  53.                         } else {  
  54.                             alert(data.message);  
  55.                             //继续失败的逻辑...  
  56.                         }  
  57.                      },  
  58.                      //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.  
  59.                      //换句话说如果后台的异常没有捕获到,则认为是error.  
  60.                     error: function (s, xml, status, e){  
  61.                         console.info('上传图片失败:未知异常!');  
  62.                      }   
  63.                 });  
  64.              }  
  65.         });  
  66.     });  
  67.     </script>  
  68.   </head>  
  69.   <body>  
  70.     <form id="form" method="post" enctype="multipart/form-data">  
  71.         <input id="username" name="username" type="text" value="请输入姓名"/>  
  72.         <input id="password" name="password" type="password" value="请输入密码"/>  
  73.         <input id="photo" name="photo" type="file"/>  
  74.         <img id="img" src=""/>  
  75.         <input id="upload" type="button" value="上传"/>  
  76.     </form>  
  77.     <div id="prompt"></div>                               
  78.   </body>  
  79. </html>  
[html]  view plain copy
  1. <!--   
  2. 上传多个文件并携带多个参数.  
  3. 扩展:可以通过jquery扩展为添加文件选择框,去除文件选择框,而不是写死只能上传几个文件.  
  4.  @author IluckySi  
  5.  @since 20150213  
  6.  -->  
  7. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  8. <%  
  9. String path = request.getContextPath();  
  10. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  11. %>  
  12. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  13. <html>  
  14.   <head>  
  15.      <base href="<%=basePath%>">  
  16.     <title>test</title>  
  17.     <meta http-equiv="pragma" content="no-cache">  
  18.     <meta http-equiv="cache-control" content="no-cache">  
  19.     <meta http-equiv="expires" content="0">      
  20.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  21.     <meta http-equiv="description" content="This is my page">  
  22.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  23.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  24.     <script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>  
  25.     <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>  
  26.     <script>  
  27.     var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload2.mvc';  
  28.     $(function(){  
  29.         $('#upload').click(function(e){  
  30.             var username = $('#username').val();  
  31.             var password = $('#password').val();  
  32.             var isValidate = false;  
  33.             if(username == '' || password == '') {  
  34.                   $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');  
  35.             } else {  
  36.                 isValidate = true;  
  37.             }  
  38.             if(isValidate) {  
  39.                 $.ajaxFileUpload({  
  40.                     url:uploadUrl,  
  41.                     secureuri:false,  
  42.                     //文件选择框的id属性.  
  43.                     fileElementId:['photo1', 'photo2', 'photo3'],  
  44.                     dataType: 'json',  
  45.                     data:{  
  46.                         username:username,  
  47.                         password:password     
  48.                     },   
  49.                     //注意:这里的success方法代表的是前台成功接收了后台返回的数据.  
  50.                     success: function (data, status) {  
  51.                         if(data.result == 'success') {  
  52.                             alert(data.message);  
  53.                             //继续成功的逻辑...  
  54.                         } else {  
  55.                             alert(data.message);  
  56.                             //继续失败的逻辑...  
  57.                         }  
  58.                      },  
  59.                      //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.  
  60.                      //换句话说如果后台的异常没有捕获到,则认为是error.  
  61.                     error: function (s, xml, status, e){  
  62.                         console.info('上传图片失败:未知异常!');  
  63.                      }   
  64.                 });  
  65.              }  
  66.         });  
  67.     });  
  68.     </script>  
  69.   </head>  
  70.   <body>  
  71.     <form id="form" method="post" enctype="multipart/form-data">  
  72.         <input id="username" name="username" type="text" value="请输入姓名"/>  
  73.         <input id="password" name="password" type="password" value="请输入密码"/>  
  74.         <input id="photo1" name="photo" type="file"/>  
  75.         <input id="photo2" name="photo" type="file"/>  
  76.         <input id="photo3" name="photo" type="file"/>  
  77.         <input id="upload" type="button" value="上传"/>  
  78.     </form>  
  79.     <div id="prompt"></div>                               
  80.   </body>  
  81. </html>  
[html]  view plain copy
  1. <!--   
  2. 上传一个文件并携带多个参数,同时上传完成之后,及时显示.  
  3.  @author IluckySi  
  4.  @since 20150213  
  5.  -->  
  6. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  7. <%  
  8. String path = request.getContextPath();  
  9. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  10. %>  
  11. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  12. <html>  
  13.   <head>  
  14.      <base href="<%=basePath%>">  
  15.     <title>test</title>  
  16.     <meta http-equiv="pragma" content="no-cache">  
  17.     <meta http-equiv="cache-control" content="no-cache">  
  18.     <meta http-equiv="expires" content="0">      
  19.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.     <meta http-equiv="description" content="This is my page">  
  21.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  22.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  23.     <script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>  
  24.     <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>  
  25.     <script>  
  26.     var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload3.mvc';  
  27.     $(function(){  
  28.         $('#upload').click(function(e){  
  29.             var username = $('#username').val();  
  30.             var password = $('#password').val();  
  31.             var isValidate = false;  
  32.             if(username == '' || password == '') {  
  33.                   $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');  
  34.             } else {  
  35.                 isValidate = true;  
  36.             }  
  37.             if(isValidate) {  
  38.                 $.ajaxFileUpload({  
  39.                     url:uploadUrl,  
  40.                     secureuri:false,  
  41.                     //文件选择框的id属性.  
  42.                     fileElementId:'photo',  
  43.                     dataType: 'json',  
  44.                     data:{  
  45.                         username:username,  
  46.                         password:password     
  47.                     },   
  48.                     //注意:这里的success方法代表的是前台成功接收了后台返回的数据.  
  49.                     success: function (data, status) {  
  50.                         if(data.result == 'success') {  
  51.                             //及时预览.  
  52.                             $('#img').attr('src', data.message).  
  53.                                 attr('width', '100px').  
  54.                                 attr('height', '100px');  
  55.                             //继续成功的逻辑...  
  56.                         } else {  
  57.                             alert(data.message);  
  58.                             //继续失败的逻辑...  
  59.                         }  
  60.                      },  
  61.                      //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.  
  62.                      //换句话说如果后台的异常没有捕获到,则认为是error.  
  63.                     error: function (s, xml, status, e){  
  64.                         console.info('上传图片失败:未知异常!');  
  65.                      }   
  66.                 });  
  67.              }  
  68.         });  
  69.     });  
  70.     </script>  
  71.   </head>  
  72.   <body>  
  73.     <form id="form" method="post" enctype="multipart/form-data">  
  74.         <input id="username" name="username" type="text" value="请输入姓名"/>  
  75.         <input id="password" name="password" type="password" value="请输入密码"/>  
  76.         <input id="photo" name="photo" type="file"/>  
  77.         <img id="img" src=""/>  
  78.         <input id="upload" type="button" value="上传"/>  
  79.     </form>  
  80.     <div id="prompt"></div>                               
  81.   </body>  
  82. </html>  
[html]  view plain copy
  1. <!--   
  2. 上传一个文件并携带多个参数,上传之前实现预览.  
  3. 难点:  
  4. 对于Chrome,Firefox和IE10使用 FileReader来实现.  
  5. 对于IE6~9使用滤镜 filter:progid:DXImageTransform.Microsoft.AlphaImageLoader来实现.  
  6.  @author IluckySi  
  7.  @since 20150213  
  8.  -->  
  9. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  10. <%  
  11. String path = request.getContextPath();  
  12. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  13. %>  
  14. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  15. <html>  
  16.   <head>  
  17.      <base href="<%=basePath%>">  
  18.     <title>test</title>  
  19.     <meta http-equiv="pragma" content="no-cache">  
  20.     <meta http-equiv="cache-control" content="no-cache">  
  21.     <meta http-equiv="expires" content="0">      
  22.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  23.     <meta http-equiv="description" content="This is my page">  
  24.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  25.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  26.     <script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>  
  27.     <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>  
  28.     <script>  
  29.     var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload4.mvc';  
  30.     $(function(){  
  31.         $('#upload').click(function(e){  
  32.             var username = $('#username').val();  
  33.             var password = $('#password').val();  
  34.             var isValidate = false;  
  35.             if(username == '' || password == '') {  
  36.                   $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');  
  37.             } else {  
  38.                 isValidate = true;  
  39.             }  
  40.             if(isValidate) {  
  41.                 $.ajaxFileUpload({  
  42.                     url:uploadUrl,  
  43.                     secureuri:false,  
  44.                     //文件选择框的id属性.  
  45.                     fileElementId:'photo',  
  46.                     dataType: 'json',  
  47.                     data:{  
  48.                         username:username,  
  49.                         password:password     
  50.                     },   
  51.                     //注意:这里的success方法代表的是前台成功接收了后台返回的数据.  
  52.                     success: function (data, status) {  
  53.                         if(data.result == 'success') {  
  54.                             alert(data.message);  
  55.                             //继续成功的逻辑...  
  56.                         } else {  
  57.                             alert(data.message);  
  58.                             //继续失败的逻辑...  
  59.                         }  
  60.                      },  
  61.                      //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.  
  62.                      //换句话说如果后台的异常没有捕获到,则认为是error.  
  63.                     error: function (s, xml, status, e){  
  64.                         console.info('上传图片失败:未知异常!');  
  65.                      }   
  66.                 });  
  67.              }  
  68.         });  
  69.     });  
  70.       
  71.     //重点:图片预览.  
  72.     function preview(file){    
  73.         var preview = document.getElementById('preview');    
  74.         if (file.files && file.files[0]) {    
  75.             var reader = new FileReader();    
  76.             reader.onload = function(event){    
  77.                 preview.innerHTML = '<img src="' + event.target.result + '" width="100px" height="100px"/>';    
  78.             };     
  79.             reader.readAsDataURL(file.files[0]);    
  80.         } else {    
  81.             //没有用IE6~9进行测试.  
  82.             preview.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';    
  83.         }    
  84.     }    
  85.     </script>  
  86.   </head>  
  87.   <body>  
  88.     <form id="form" method="post" enctype="multipart/form-data">  
  89.         <input id="username" name="username" type="text" value="请输入姓名"/>  
  90.         <input id="password" name="password" type="password" value="请输入密码"/>  
  91.         <input id="photo" name="photo" type="file" onchange="preview(this)"/>  
  92.         <div id="preview"></div>  
  93.         <input id="upload" type="button" value="上传"/>  
  94.     </form>  
  95.     <div id="prompt"></div>                               
  96.   </body>  
  97. </html>  
[html]  view plain copy
  1. <!--   
  2. 上传一个文件,并携带多个参数.   
  3. <p>通过css将界面完善的更加人性化:点击图片选择文件.  
  4.  @author IluckySi  
  5.  @since 20150226  
  6.  -->  
  7. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  8. <%  
  9. String path = request.getContextPath();  
  10. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";  
  11. %>  
  12. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  13. <html>  
  14.   <head>  
  15.      <base href="<%=basePath%>">  
  16.     <title>test</title>  
  17.     <meta http-equiv="pragma" content="no-cache">  
  18.     <meta http-equiv="cache-control" content="no-cache">  
  19.     <meta http-equiv="expires" content="0">      
  20.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  21.     <meta http-equiv="description" content="This is my page">  
  22.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  23.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  24.     <script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>  
  25.     <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>  
  26.     <style type="text/css">  
  27.     .fileDiv{  
  28.         width:100px;  
  29.         height:40px;   
  30.         background:url(image/test.png);  
  31.         overflow:hidden;  
  32.         position:relative;  
  33.     }  
  34.     .photo{  
  35.         position:absolute;  
  36.         top:-100px;  
  37.     }  
  38.     .upFileButton{  
  39.         width:100px;  
  40.         height:40px;  
  41.         opacity:0;  
  42.         filter:alpha(opacity=0);  
  43.         cursor:pointer;  
  44.     }  
  45.     </style>  
  46.     <script>  
  47.     var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload5.mvc';  
  48.     $(function(){  
  49.         $('#upload').click(function(e){  
  50.             var username = $('#username').val();  
  51.             var password = $('#password').val();  
  52.             var isValidate = false;  
  53.             if(username == '' || password == '') {  
  54.                   $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');  
  55.             } else {  
  56.                 isValidate = true;  
  57.             }  
  58.             if(isValidate) {  
  59.                 $.ajaxFileUpload({  
  60.                     url:uploadUrl,  
  61.                     secureuri:false,  
  62.                     //文件选择框的id属性.  
  63.                     fileElementId:'photo',  
  64.                     dataType: 'json',  
  65.                     data:{  
  66.                         username:username,  
  67.                         password:password     
  68.                     },   
  69.                     //注意:这里的success方法代表的是前台成功接收了后台返回的数据.  
  70.                     success: function (data, status) {  
  71.                         if(data.result == 'success') {  
  72.                             alert(data.message);  
  73.                             //继续成功的逻辑...  
  74.                         } else {  
  75.                             alert(data.message);  
  76.                             //继续失败的逻辑...  
  77.                         }  
  78.                      },  
  79.                      //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.  
  80.                      //换句话说如果后台的异常没有捕获到,则认为是error.  
  81.                     error: function (s, xml, status, e){  
  82.                         console.info('上传图片失败:未知异常!');  
  83.                      }   
  84.                 });  
  85.              }  
  86.         });  
  87.     });  
  88.     </script>  
  89.   </head>  
  90.   <body>  
  91.     <form id="form" method="post" enctype="multipart/form-data">  
  92.         <input id="username" name="username" type="text" value="请输入姓名"/>  
  93.         <input id="password" name="password" type="password" value="请输入密码"/>  
  94.         <div id="fileDiv" class="fileDiv">  
  95.             <input type="file" id="photo" name="photo" class="photo" onchange="document.getElementById('photoName').innerHTML=this.value"/>  
  96.             <input type="button" class="upFileButton" onclick="document.getElementById('photo').click()" />  
  97.         </div>  
  98.         <div id="photoName">图片文件名称</div>  
  99.         <input id="upload" class="upload" type="button" value="上传"/>  
  100.     </form>  
  101.     <div id="prompt"></div>   
  102.   </body>  
  103. </html>  
  104. </p>  
e.最重要的是看ajaxfileupload.js文件,此文件进行了扩展,都是从网上找到的.

[javascript]  view plain copy
  1. // JavaScript Document  
  2. jQuery.extend({  
  3.      createUploadIframe: function(id, uri){  
  4.         //create frame  
  5.         var frameId = 'jUploadFrame' + id;  
  6.         var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';  
  7.         if(window.ActiveXObject){  
  8.             if(typeof uri== 'boolean'){  
  9.                 iframeHtml += ' src="' + 'javascript:false' + '"';  
  10.   
  11.             }  
  12.             else if(typeof uri== 'string'){  
  13.                 iframeHtml += ' src="' + uri + '"';  
  14.   
  15.             }     
  16.         }  
  17.         iframeHtml += ' />';  
  18.         jQuery(iframeHtml).appendTo(document.body);  
  19.         return jQuery('#' + frameId).get(0);              
  20.     },  
  21.       
  22.   
  23.     createUploadForm: function(id, fileElementId, data) {  
  24.         //create form   
  25.         var formId = 'jUploadForm' + id;  
  26.         var fileId = 'jUploadFile' + id;  
  27.         var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');      
  28.         //使ajaxfileupload支持增加附加参数.  
  29.         if(data){  
  30.             for(var i in data){  
  31.                 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);  
  32.             }             
  33.         }         
  34.         //ajaxFileupload默认是只能上传一个文件,替换如下代码地实现多个文件上传.  
  35.         if (typeof(fileElementId) == 'string') {  
  36.           fileElementId = [fileElementId];  
  37.         }  
  38.        for (var i in fileElementId) {  
  39.           var oldElement = jQuery('#' + fileElementId[i]);  
  40.           var newElement = jQuery(oldElement).clone();  
  41.           jQuery(oldElement).attr('id', fileId);  
  42.           jQuery(oldElement).before(newElement);  
  43.           jQuery(oldElement).appendTo(form);  
  44.       
  45.       }  
  46.       /*var oldElement = jQuery('#' + fileElementId); 
  47.       var newElement = jQuery(oldElement).clone(); 
  48.       jQuery(oldElement).attr('id', fileId); 
  49.       jQuery(oldElement).before(newElement); 
  50.       jQuery(oldElement).appendTo(form);*/  
  51.       //set attributes  
  52.       jQuery(form).css('position''absolute');  
  53.       jQuery(form).css('top''-1200px');  
  54.       jQuery(form).css('left''-1200px');  
  55.       jQuery(form).appendTo('body');   
  56.       return form;  
  57.     },  
  58.   
  59.     ajaxFileUpload: function(s) {  
  60.         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout          
  61.         s = jQuery.extend({}, jQuery.ajaxSettings, s);  
  62.         var id = new Date().getTime();         
  63.         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));  
  64.         var io = jQuery.createUploadIframe(id, s.secureuri);  
  65.         var frameId = 'jUploadFrame' + id;  
  66.         var formId = 'jUploadForm' + id;          
  67.         // Watch for a new set of requests  
  68.         if ( s.global && ! jQuery.active++ ){  
  69.             jQuery.event.trigger( "ajaxStart" );  
  70.         }              
  71.         var requestDone = false;  
  72.         // Create the request object  
  73.         var xml = {};     
  74.         if ( s.global )  
  75.             jQuery.event.trigger("ajaxSend", [xml, s]);  
  76.         // Wait for a response to come back  
  77.         var uploadCallback = function(isTimeout){             
  78.             var io = document.getElementById(frameId);  
  79.             try {     
  80.                 if(io.contentWindow){  
  81.                      xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;  
  82.                      xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;  
  83.                        
  84.                 }else if(io.contentDocument){  
  85.                      xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;  
  86.                      xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;  
  87.                 }                         
  88.             }catch(e){  
  89.                 jQuery.handleError(s, xml, null, e);  
  90.             }  
  91.             if (xml || isTimeout == "timeout"){               
  92.                 requestDone = true;  
  93.                 var status;  
  94.                 try {  
  95.                     status = isTimeout != "timeout" ? "success" : "error";  
  96.                     // Make sure that the request was successful or notmodified  
  97.                     if ( status != "error" ){  
  98.                         // process the data (runs the xml through httpData regardless of callback)  
  99.                         var data = jQuery.uploadHttpData(xml, s.dataType );      
  100.                         // If a local callback was specified, fire it and pass it the data  
  101.                         if ( s.success )  
  102.                             s.success( data, status );  
  103.                         // Fire the global callback  
  104.                         if( s.global )  
  105.                             jQuery.event.trigger( "ajaxSuccess", [xml, s] );  
  106.                     } else  
  107.                         jQuery.handleError(s, xml, status);  
  108.                 } catch(e){  
  109.                     status = "error";  
  110.                     jQuery.handleError(s, xml, status, e);  
  111.                 }  
  112.                 // The request was completed  
  113.                 if( s.global )  
  114.                     jQuery.event.trigger( "ajaxComplete", [xml, s] );  
  115.                 // Handle the global AJAX counter  
  116.                 if ( s.global && ! --jQuery.active )  
  117.                     jQuery.event.trigger( "ajaxStop" );  
  118.                 // Process result  
  119.                 if ( s.complete )  
  120.                     s.complete(xml, status);  
  121.                 jQuery(io).unbind();  
  122.                 setTimeout(function(){    
  123.                     try {  
  124.                         jQuery(io).remove();  
  125.                         jQuery(form).remove();    
  126.                           
  127.                     } catch(e){  
  128.                         jQuery.handleError(s, xml, null, e);  
  129.                     }                                     
  130.                 }, 100);  
  131.                 xml = null;  
  132.             }  
  133.         };  
  134.         // Timeout checker  
  135.         if ( s.timeout > 0 ){  
  136.             setTimeout(function(){  
  137.                 // Check to see if the request is still happening  
  138.                 if( !requestDone ) uploadCallback( "timeout" );  
  139.             }, s.timeout);  
  140.         }  
  141.         try {  
  142.             var form = jQuery('#' + formId);  
  143.             jQuery(form).attr('action', s.url);  
  144.             jQuery(form).attr('method''POST');  
  145.             jQuery(form).attr('target', frameId);  
  146.             if(form.encoding){  
  147.                 jQuery(form).attr('encoding''multipart/form-data');                 
  148.             }  
  149.             else{     
  150.                 jQuery(form).attr('enctype''multipart/form-data');              
  151.             }             
  152.             jQuery(form).submit();  
  153.   
  154.         } catch(e) {              
  155.             jQuery.handleError(s, xml, null, e);  
  156.         }  
  157.         jQuery('#' + frameId).load(uploadCallback);  
  158.         return {abort: function () {}};   
  159.   
  160.     },  
  161.   
  162.     uploadHttpData: function( r, type ) {  
  163.         var data = !type;  
  164.         data = type == "xml" || data ? r.responseXML : r.responseText;  
  165.         // If the type is "script", eval it in global context  
  166.         if (type == "script" )  
  167.             jQuery.globalEval( data );  
  168.         // Get the JavaScript object, if JSON is used.  
  169.         if (type == "json" )  
  170.             //针对ajaxfileupload返回json带<pre>标签解,  
  171.             //决方案为将eval( "data = " + data );换成data = jQuery.parseJSON(jQuery(data).text());  
  172.             //eval( "data = " + data );  
  173.             data = jQuery.parseJSON(jQuery(data).text());  
  174.         // evaluate scripts within html  
  175.         if (type == "html" )  
  176.             jQuery("<div>").html(data).evalScripts();  
  177.   
  178.         return data;  
  179.     },  
  180.       
  181.     //针对ajaxfileupload.js结合低版本jquery报异常:TypeError: jQuery.handleError is not a function,添加如下代码.  
  182.     handleError: function( s, xhr, status, e )      {    
  183.         // If a local callback was specified, fire it  
  184.         if ( s.error ) {    
  185.             s.error.call( s.context || s, xhr, status, e );    
  186.         }    
  187.         // Fire the global callback    
  188.         if ( s.global ) {    
  189.             (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );    
  190.         }    
  191.     }   
  192. });  
大功告成, 亲以后有什么简答的上传工作,就交给他吧!!!


你可能感兴趣的:(jquery)