文件的上傳、文件的下載、I18N國際化

一:文件上傳

01.文件上傳準備

1):上傳控件所在的<form>表單的method,必須POST:

        因爲GET方式的數據大小不能超過2kb,而POST沒有大小限制.

2):上傳控件得使用typefile的類型.<input type="file" name="headImg"/>

3):表單的編碼方式必須是二進制編碼.<form enctype="multipart/form-data">

        注意:使用二進制的編碼之後form enctype="multipart/form-data">,在Servlet中再也不能通過request.getParameter方法來獲取參數了,設置編碼也沒有效果

02.基於Apache FileUpload組件文件上傳操作

依賴的jar:

    1):commons-fileupload-1.2.2.jar

    2):commons-io-1.4.jar

參考文檔:

    commons-fileupload-1.2.2\site\index.html

hello world版本,建議自己看着文檔寫一遍

@WebServlet("/upload")
public class UploadServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest req, HttpServletResponse resp){
        //解析和檢查請求:請求方式是否是POST,請求編碼是否是enctype="multipart/form-data"
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if(!isMultipart){
            return;
        }
        //1:創建FileItemFactory對象
        //FileItemFactory是用來創建FileItem對象的.
        //FileItem對象:form表單中的表單控件的封裝
        try {
        FileItemFactory factory = new DiskFileItemFactory();
        //2:創建文件上傳處理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //3:解析請求
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                String fieldName = item.getFieldName();//獲取表單控件的name屬性值(參數名)
                if(item.isFormField()){
                    //普通表單控件
                    String value = item.getString("UTF-8");//獲取當前普通表單控件的參數值
                    System.out.println(fieldName+"--"+value);
                }else{
                    //表單上傳控件
                    System.out.println(fieldName+"+"+item.getName());
                    item.write(new File("D:/",item.getName()));//把二進制數據寫到哪一個文件中
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

03.上傳文件的名稱處理

1):文件名處理:

        IE6問題:通過FileItem.getName方法獲取上傳文件的名稱,此時會帶有路徑:

        其他瀏覽器:outman.png.  IE6:C:/123/outman.png.

        使用FilenameUtils.getName(path);

        上傳文件名稱:給上傳的文件起唯一的名稱:UUID.

        String fileName = UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(item.getName());

        上傳文件的保存路徑:一般的,把上傳文件保存到應用裏面.

2):緩存大小和臨時目錄:

        超過多少就不直接存放與內存了(緩存大小):默認值是10KB.

        不放在內存,會放在哪個位置(臨時目錄):默認Tomcat根/temp目錄.不建議修改

        DiskFileItemFactory factory = new DiskFileItemFactory();
        //設置緩存大小
        factory.setSizeThreshold(20*1024);
        //設置臨時目錄
        factory.setRepository(repository);

3):文件類型約束:  

    //獲取當前上傳文件的MIME類型

    String mimeType = super.getServletContext().getMimeType(item.getName());

servlet代碼:

        //允許接受的圖片類型
        private static final String ALLOWED_IMAGE_TYPE="png;gif;jpg;jpeg";

        //上傳文件的拓展名
        String ext = FilenameUtils.getExtension(item.getName());
        String[] allowedImageType = ALLOWED_IMAGE_TYPE.split(";");      
        //當前上下文的類型不在圖片允許的格式之內
        if(!Arrays.asList(allowedImageType).contains(ext)){
                req.setAttribute("errorMsq","親,請上傳圖片文件");
                req.getRequestDispatcher("/input.jsp").forward(req,resp);
                return ;//結束方法
        }

jsp的代碼:

        <span style="color: red;">${errorMsg}</span>

4)抽取文件上傳工具方法.

    @WebServlet("/upload")
    public class UploadServlet extends HttpServlet{
        private static final long serialVersionUID = 1L;
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try {
                FileUtil.upload(req);
            } catch (LogicException e) {
                String errorMsge = e.getMessage();
                req.setAttribute("errorMsg", errorMsge);
                req.getRequestDispatcher("/input.jsp").forward(req, resp);
            }
        }
    }


    public class FileUtil {
        //允許接收的圖片類型
            private static final String ALLOWED_IMAGE_TYPE = "gif;jpq;jpeg";
            public static void upload(HttpServletRequest req) {     
            try{
                    ......
                    if (!list.contains(ext)) {
                            throw new LogicException("親!請上傳正確的圖片格式!");
                    }
                    ......
            } catch (LogicException e) {
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
5):上傳文件大小約束:

    情況1: 單個文件超過指定的大小.           upload.setFileSizeMax(1024 * 1024 * 2);

    情況2: 該次請求的全部數據超過指定的大小   upload.setSizeMax(1024*1024*3)

    catch (FileSizeLimitExceededException e) {
    throw new LogicException("親,單個文件大小不能超過2M",e);
    } catch (SizeLimitExceededException e) {
        throw new LogicException("親,該次請求的大小不能超過3M",e);
    } catch (LogicException e) {
        throw e;//繼續拋出異常給調用者(UploadServlet)
    } catch (Exception e) {
        e.printStackTrace();
    }
6):使用Map封裝請求信息(拓展):

    @Data
    public class User {
        private String username;
        private String email;
        private String imageUrl;//圖片保存的路徑:/upload/123.png       JSP: <img src="${user.imageUrl}"/> 
        private String imageName;//圖片的原始名稱
    }

    @Data
    public class CFiled {

        private String imageUrl;
        private String imageName;
    }

    @WebServlet("/upload")
    public class UploadServlet extends HttpServlet{
        private static final long serialVersionUID = 1L;
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try {

                User user = new User();
                HashMap<String,String> map = new HashMap<>();
                HashMap<String,CFiled> binaryMap = new HashMap<>();
                FileUtil.upload(req,map,binaryMap);
                user.setEmail(map.get("email"));
                user.setUsername(map.get("username"));
                user.setImageName(binaryMap.get("headimg").getImageName());
                user.setImageUrl(binaryMap.get("headimg").getImageUrl());
                System.out.println(map);
                System.out.println(binaryMap);
                System.out.println(user);
                req.setAttribute("u", user);
                req.getRequestDispatcher("/show.jsp").forward(req, resp);

            } catch (LogicException e) {
                String errorMsge = e.getMessage();
                req.setAttribute("errorMsg", errorMsge);
                req.getRequestDispatcher("/input.jsp").forward(req, resp);
            }
        }
    }

    public class FileUtil {
    private static final String ALLOWED_IMAGE_TYPE = "png;gif;jpq;jpeg";
    public static void upload(HttpServletRequest req, HashMap<String,String> map, HashMap<String,CFiled> binarytMap) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (!isMultipart) {
            return;
        }
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(1024 * 1024 * 2);//2M
            upload.setSizeMax(1024*1024*3);//3M
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                String fieldName = item.getFieldName();//獲取表單控件的name屬性值(參數名)
                if (item.isFormField()) {
                    //普通表單控件
                    String value = item.getString("UTF-8");//獲取當前普通表單控件的參數值
                    map.put(fieldName, value);
                } else {
                    //--------------------------------------------
                    //上傳文件的拓展名
                    String ext = FilenameUtils.getExtension(item.getName());
                    String[] allowedImageType = ALLOWED_IMAGE_TYPE.split(";");
                    List<String> list = Arrays.asList(allowedImageType);
                    if (!list.contains(ext)) {
                        throw new LogicException("親!請上傳正確的圖片格式!");
                    }
                    //--------------------------------------------
                    //表單上傳控件
                    System.out.println("上傳文件的名稱:" + FilenameUtils.getName(item.getName()));
                    String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(item.getName());
                    String dir = req.getServletContext().getRealPath("/upload");
                    item.write(new File(dir, fileName));//把二進制數據寫到哪一個文件中
                    CFiled CFiled = new CFiled();
                    CFiled.setImageName(FilenameUtils.getName(item.getName()));
                    CFiled.setImageUrl("/upload/"+fileName);
                    binarytMap.put(fieldName,CFiled);
                }
            }
        } catch (FileSizeLimitExceededException e) {
            throw new LogicException("親,單個文件大小不能超過2M",e);
        } catch (SizeLimitExceededException e) {
            throw new LogicException("親,該次請求的大小不能超過3M",e);
        } catch (LogicException e) {
            throw e;//繼續拋出異常給調用者(UploadServlet)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二:文件的下載

IE和非IE的文件名亂碼處理:

list.jsp文件:

        <h3>下載資源列表</h3>
        <a href="/down?filename=butter.rar">butter.rar</a><br/>
        <a href="/down?filename=超人superman.rar">超人Superman</a>

Servlet文件:

        @WebServlet("/down")
        public class DownloadServlet extends HttpServlet{

            private static final long serialVersionUID = 1L;
            protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                //0:權限檢查/積分檢查
                //1:獲取被下載的資源文件名稱
                String fileName = req.getParameter("filename");
                if(fileName!=null && !"".equals(fileName.trim())){
                    fileName = new String(fileName.getBytes("ISO-8859-1"),"utf-8");
                    System.out.println(fileName);
                }
                //2:從服務器中找到被下載資源的絕對路徑
                String realPath = super.getServletContext().getRealPath("/WEB-INF/download/"+fileName);
                //=======================================
                //①:告訴瀏覽器不要直接打開文件,而是彈出下載框,保存文件
                resp.setContentType("application/x-msdownload");
                //②:設置下載文件的建議保存名稱
                String userAgent = req.getHeader("User-Agent");
                if(userAgent.contains("like")){
                    //IE
                    fileName = URLEncoder.encode(fileName,"UTF-8");
                }else{
                    //非IE
                    fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
                }
                resp.setHeader("Content-Disposition","attachment;filename="+fileName); 
                //=======================================
                //3:磁盤中的文件讀取到--->程序中來--->瀏覽器(拷貝操作)
                Files.copy(Paths.get(realPath), resp.getOutputStream());
            }
        }

三: I18N國際化

04.國際化了解上

        軟件的本地化,一個軟件在某個國家或地區使用時,採用該國家或地區的語言,數字,貨幣,日期等習慣.

軟件的國際化:軟件開發時,讓它能支持多個國家和地區的本地化應用.使得應用軟件能夠適應多個地區的語言和

文化習俗的習慣.隨用戶區域信息而變化的數據稱爲本地信息敏感數據.例如數字,貨幣等數據.應用程序的國際

化就是在應用軟件的設計階段,使軟件能夠支持多個國家和地區的使用習慣.

05.國際化了解下

        @Test
    public void test1() throws Exception {
        System.out.println(Locale.CHINA);
        System.out.println(Locale.US);
        System.out.println(Locale.FRANCE);
        System.out.println(Locale.TAIWAN);
    }

    @Test
    public void testFormat() throws Exception {
        System.out.println(new Date());
        String format = DateFormat.getInstance().format(new Date());
        System.out.println(format);
    }
    //¥123,456,789.89
    //123?456?789,89 €
    //?123,456,789.89
    //$123,456,789.89
    @Test
    public void testNumberFormat() throws Exception {
        Double money = 123456789.89;
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
        System.out.println(format.format(money));
    }
    public static void main(String[] args) {
            String pattern = "我是{3},你是{5},他是{4},她是{2},它是{1}";
            String str = MessageFormat.format(pattern, "A","B","C","D","E");
            System.out.println(str);
        }

    @Test
    public void testSql() throws Exception {
        String sql = "SELECT * FROM {0} {1}";
        String ret = MessageFormat.format(sql, "product","WHERE productName LIKE = ?");
        System.out.println(ret);
    }
    public static void main(String[] args) {
        //ResourceBundle可以獲取資源文件,獲取其中的信息
        ResourceBundle rb = ResourceBundle.getBundle("app",Locale.CHINA);
        String username = rb.getString("username");
        String company = rb.getString("company");
        System.out.println(username+"---->"+company);
    }

知識點:

    1):基於Apache 的fileUploaed組件完成文件的上傳操作.
    2):文件上傳做控制:
            1):文件名處理.
            2):上傳文件的類型約束.
            3):上傳文件的大小限制.
    3):文件下載操作.
    -----------------------------------------------
    任務:
        1):高級查詢和分頁查詢,鞏固,加強.
        2):去淘寶,去京東體驗購物車.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章