jsp 使用Common-FileUpload組件檔案上傳及限制上傳類型,

來源:互聯網
上載者:User

jsp 使用Common-FileUpload組件檔案上傳及限制上傳類型,

1、將commons-fileupload-1.3.3.jar複製到Web應用的lib檔案夾下,在WebRoot目錄下建立limit.jsp頁面,在該頁面中添加一個檔案域的表單,設定類型為    multipart/form-data。代碼如下:

<body>    <h2>上傳圖書課件</h2>    <form action="LimitFile" name="one" enctype="multipart/form-data" method="post">    選擇一個rar檔案:    <input type="file" name="fileupload" value="upload" />     <input type="submit" value="上傳"> <input type="reset" value="取消">    </form>  </body>

 

  上述代碼指定提交後將請求提交給LimitFile處理,LimitFile(Servlet)用來處理上傳檔案及判斷檔案類型是否匹配,顯示上傳結果。

2、建立名為LimitFile的Servlet,並在doPost()方法中編寫實現代碼,如下所示:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        response.setContentType("text/html");        PrintWriter out = response.getWriter();        String uploadpath = "";        DiskFileItemFactory factory = new DiskFileItemFactory();        //設定是否使用臨時檔案儲存解析出來的資料的那個臨界值,該方法傳入參數的單位是位元組。        factory.setSizeThreshold(30 * 1024);        //用於設定setSizeThreshold()方法中提到的臨時檔案的存放目錄,這裡要求使用絕對路徑。        factory.setRepository(factory.getRepository());        ServletFileUpload upload = new ServletFileUpload(factory);        List list = null;        try{            list = upload.parseRequest(request);            String[]  limit = new String[]{".jpg", ".gif", ".png", ".bmp"};            //定義限制的檔案類型            SuffixFileFilter filter = new SuffixFileFilter(limit);            //擷取SuffixFileFilter執行個體            Iterator iterator = list.iterator();            while(iterator.hasNext()){                FileItem item =(FileItem)iterator.next();                if(!item.isFormField()){                    String filePath = item.getName();                    if(filePath != null){                        File filename= new File(filePath);                        File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");                        uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;                        //因為路徑後面多了個";"號,所以要去掉                        uploadpath = uploadpath.substring(0, uploadpath.length()-1);                        File saveFile = new File(uploadpath,filename.getName());                        boolean flag = filter.accept(saveFile);                        if(flag){                            out.print("禁止上傳傳圖片檔案");                            break;                        }else{                            try {                                item.write(saveFile);                                out.print("檔案上傳成功");                            } catch (Exception e) {                                out.print("檔案上傳失敗了");                                e.printStackTrace();                            }                        }                    }                }            }        }catch(FileUploadException e){            e.printStackTrace();        }    }

上述代碼在位元組串數組limit中定義了不允許上傳的檔案類型,然後將該數組傳遞給SuffixFileFilter類的建構函式。在通過該類的accept()方法驗證當前上傳的檔案是否符合條件。最後將檔案儲存到項目的upload目錄下。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.