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;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM