ajaxFileUpload文件上传

一、简介

  ajaxFileUpload是一种异步的文件上传控件,通过ajax进行文件上传,并获取上传处理结果。在很多时候我们需要使用到文件上传的功能,但是不需要使用那些强大的上传插件。此时就可以使用ajaxFileUpload。它基于jquery,本质是使用iframe完成上传。下载地址为:下载 。

二、实例  

  网页代码如下:

 1 <%@ page contentType="text/html; charset=UTF-8"%>
 2 <!DOCTYPE html>
 3 <html>
 4 <head>
 5 <title>文件上传</title>
 6 </head>
 7 <body>
 8   <div>
 9         <form id="formItem">
10             <div id="contentTable" style="border:0px;">
11                 <h1 class="title" style="font-size:15px;border-bottom:1pxsolid#DFE3E6;">excel文件上传</h1>
12                 <table width="80%">
13                 <tr>
14                     <td width="30%" align="right">
15                     选择要上传的excel文件
16                     </td>
17                     <td width="70%" style="text-align:center;">
18                     <input type="file" id="file1" name="file"/>
19                     </td>
20                 </tr>
21                 </table>
22                 <div>
23                     <input type="button" value="导入&nbsp;"/>
24                 </div>
25             </div>
26         </form>
27   </div>
28 <scriptsrc="${pageContext.request.contextPath}/res/js/jquery-1.9.1.min.js"type="text/javascript"></script>
29 <scriptsrc="${pageContext.request.contextPath}/res/js/ajaxfileupload.js"></script>
30 <scripttype="text/javascript">
31 var flag=false;
32 $(function(){
33   //文件类型过滤
34   $(":button").click(function(){
35       varfilepath = $("#file1").val();
36       vararr = new Array();
37       arr = filepath.split(".");
38       var fileType = new Array(["xls"],["xlsx"]);
39       for(var i = 0; i < fileType.length; i++){
40           if(arr[1] == fileType[i]){
41               flag = true;
42           }
43       }
44       if(flag){
45           ajaxFileUpload();
46       }else{
47           alert("请选择excel文件上传")
48           return false;
49       }
50   })
51 });
52     
53 functionajaxFileUpload(){
54   $.ajaxFileUpload
55   (
56     {
57       url : '${pageContext.request.contextPath}/file/upload.action',//用于文件上传的服务器端请求地址
58       secureuri : false,//一般设置为false
59       fileElementId : 'file1',//文件上传空间的id属性
60       dataType : 'json',//返回值类型一般设置为json
61       success : function(data,status)//服务器成功响应处理函数
62       {
63           if(data){
64               alert("上传成功!");
65               $("#file1").val("");
66           }
67         flag = false;
68       },
69       error : function(data,status,e)//服务器响应失败处理函数
70       {
71         alert(e);
72       }
73     }
74   )
75   return false;
76 }
77 </script>
78 </body>
79 </html>

  服务器端代码如下:

    /**
    *使用springmvc进行文件上传处理
    */
    @RequestMapping("upload")
    @ResponseBody
    public boolean upload(HttpServletRequest request, HttpServletResponse response ) throws UnsupportedEncodingException
    {
        String path = request.getSession().getServletContext().getRealPath("");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        request.setCharacterEncoding("UTF-8");
        path = String.format("%s\\%s\\%s\\%s\\%s\\%s", path, "file", "upload", calendar.get(calendar.YEAR),
                calendar.get(calendar.MONTH), calendar.get(calendar.DAY_OF_MONTH));
        File filepath = new File(path);
        if (!filepath.exists()) {
            filepath.mkdirs();
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件
        MultipartFile multipartFile = multipartRequest.getFile("file"); 
        String filename = multipartFile.getOriginalFilename();
        OutputStream os = null;
        InputStream is = null;
        File uploadFile = null;
        try {
            is = multipartFile.getInputStream();
            if (is != null) {
                uploadFile = new File(filepath, System.currentTimeMillis() + ".xls");
                os = new FileOutputStream(uploadFile);
                IOUtils.copy(is, os);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace(); 
            return false;
        } finally {
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(is);
        }  
        return true;
    }

posted on 2015-05-04 15:29  烟火_  阅读(3252)  评论(0编辑  收藏  举报

导航