JAVA 發送下載文件

GiseleGrang 9年前發布 | 1K 次閱讀 Java

下載文件

protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //doPost(request, response);

        //System.out.println("下載");
        response.setContentType("application/x-download");

        PropertyBean propertyBeanURL = new PropertyBean();
        propertyBeanURL.setPropertiesFile("mail.properties");
        propertyBeanURL.init();
        String tempUrl = propertyBeanURL.get("temp");

         String filePath = tempUrl+ File.separatorChar+ "CrmUpload" +File.separatorChar;
        String filedownload = filePath + "tcsl_mobile.xls";
        //String filePath = getPropertyBean("ticketFilePath"); //"E:\\CrmUpload\\";
        //String filedownload = filePath + getPropertyBean("ticketTemplatesFile");  //filePath + "mobile.xls";//文件名
        String filedisplay = "非會員電話號碼模版.xls";//下載文件時顯示的文件保存名稱
        String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);

        OutputStream outp = null;
        FileInputStream in = null;
        try
        {
            outp = response.getOutputStream();
            File truefile=new File(filedownload);
            in = new FileInputStream(truefile);

            byte[] b = new byte[1024];
            int i = 0;
            while((i = in.read(b)) > 0){
                outp.write(b, 0, i);
            }
            outp.flush();
        }
        catch(Exception e)
        {
            //System.out.println("Error!");
            logger.error(e.getMessage(),e);
        }
        finally
        {
            if(in != null)
            {
                in.close();
                in = null;
            }
            if(outp != null)
            {
                outp.close();
                outp = null;
            }
        }       
    }

接收文件(此例是接收xls文件,并解析)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        final long MAX_SIZE = 1024 * 1024 * 1;// 設置上傳文件最大為1G 1B *1024 = 1*1024 = 1M *1024 = 1G
        // 上傳文件路徑
        //String filePath = getPropertyBean("ticketFilePath"); //"E:\\CrmUpload\\";
        PropertyBean propertyBeanURL = new PropertyBean();
        propertyBeanURL.setPropertiesFile("mail.properties");
        propertyBeanURL.init();
        String tempUrl = propertyBeanURL.get("temp");

         String filePath = tempUrl+ File.separatorChar+ "CrmUpload" +File.separatorChar;
        //System.out.println(filePath);
        try {
            checkPath(filePath);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        // 臨時存放目錄
        String tempPath = filePath + "temp"+File.separator;
        try {
            checkPath(tempPath);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        // 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        // 設置上傳文件時用于臨時存放文件的內存大小,這里是5M.多于的部分將臨時存在硬盤
        dfif.setSizeThreshold(1024 * 1024 * 5);
        // 設置存放臨時文件的目錄
        dfif.setRepository(new File(tempPath));

        // 用以上工廠實例化上傳組件
        ServletFileUpload sfu = new ServletFileUpload(dfif);
        // 設置最大上傳尺寸
        sfu.setSizeMax(MAX_SIZE);

        // 從request得到 所有 上傳域的列表
        List fileList = null;
        try {
            fileList = sfu.parseRequest(request);
        } catch (FileUploadException e) {// 處理文件尺寸過大異常
            if (e instanceof SizeLimitExceededException) {
                //System.out.println("導入文件大小不能超過1M");
                out.println(showMsg("導入文件大小不能超過1M!"));
                return;
            }
            logger.error(e.getMessage(),e);
        }

        // 沒有選擇上傳文件
        if (fileList == null || fileList.size() == 0) {
            //System.out.println("請選擇導入文件");
            out.println(showMsg("請選擇導入文件"));
            return;
        }
        // 得到所有上傳的文件
        Iterator fileItr = fileList.iterator();
        // 循環處理所有文件
        while (fileItr.hasNext()) {

            FileItem fileItem = null;
            String path = null;
            double size = 0;
            // 得到當前文件
            fileItem = (FileItem) fileItr.next();

            // 忽略簡單form字段而不是上傳域的文件域(<input type="text" />等)
            if (fileItem == null || fileItem.isFormField()) {
                continue;
            }

            // 得到文件的完整路徑
            path = fileItem.getName();
            // 得到文件的大小
            size = fileItem.getSize();

            // 得到去除路徑的文件名
            String t_name = path.substring(path.lastIndexOf(File.separator) + 1);
            // 得到文件的擴展名(無擴展名時將得到全名)
            String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);

            if (!"xls".equalsIgnoreCase(t_ext)) {
                out.println(showMsg("請使用正確的電話號碼模版文件導入!"));
                break;
            }


            //生成文件名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
            String newname = sdf.format((new Date()).getTime());
            t_name = newname + RandomStringUtils.randomNumeric(3);

            // 保存的最終文件完整路徑,保存在e盤upload目錄下
            String u_name = filePath + t_name + "." + t_ext;
            String u_size = "";

            try {
                // 保存文件
                fileItem.write(new File(u_name));
                if (size > 1024 * 1024)
                    u_size = (float) Math.round(size * 100 / (1024 * 1024)) / 100 + "MB";
                else
                    u_size = (float) Math.round(size * 100 / 1024) / 100 + "KB";

                //System.out.println("文件名:" + t_name + "上傳完成。文件大小:" + u_size);
                out.println(showMsg("導入文件加載完畢,正在解析,請稍候..."));


                POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(u_name));
                HSSFWorkbook workBook = new HSSFWorkbook(fs);

                try {
                    HSSFSheet sheet = workBook.getSheetAt(0);
                    int rows = sheet.getPhysicalNumberOfRows();
                    rows = 3001; //1萬行數據
                    if (rows > 0) {
                        sheet.getMargin(Sheet.TopMargin);
                        List<MobileListDto> list = new ArrayList<MobileListDto>();              
                        for (int j = 1; j < rows; j++) {  //從第2行開始
                            HSSFRow row = sheet.getRow(j);
                            if (row == null) {
                                continue;
                            }
                            int cells = row.getLastCellNum(); // 是獲取最后一個不為空的列是第幾個
                            if (cells < 1){
                                out.println(showMsg("電話號碼文件格式不符合要求!"));
                                break;
                            }

                                HSSFCell cell0 = row.getCell(0); //姓名列
                                HSSFCell cell1 = row.getCell(1); //手機號碼列

                                // System.out.println(cell.getRichStringCellValue());
                                MobileListDto mld = new MobileListDto();
                                String rname = "";
                                String rmobile = "";

                                if (cell0 != null){
                                    switch (cell0.getCellType()) {
                                     case Cell.CELL_TYPE_STRING:
                                         rname = cell0.getRichStringCellValue().toString();                                      
                                     break;
                                     case Cell.CELL_TYPE_NUMERIC:
                                         rname = new DecimalFormat("0").format(cell0.getNumericCellValue());
                                     break;
                                    }
                                } else {
                                    rname = "";
                                }

                                if (cell1!=null) {
                                    switch (cell1.getCellType()) {
                                     case Cell.CELL_TYPE_STRING:
                                         rmobile = cell1.getRichStringCellValue().toString();                                        
                                     break;
                                     case Cell.CELL_TYPE_NUMERIC:
                                         rmobile = new DecimalFormat("0").format(cell1.getNumericCellValue());
                                     break;
                                    }                                                   
                                } else {
                                    rmobile = "";
                                }

                                rmobile = checkMobile(rmobile);
                                if ("".equals(rname)){
                                    rname = "未知";
                                }
                                //System.out.println(rname +"--"+rmobile);

                                // 手機號不為空 且 都是數字號碼
                                if (!"".equals(rmobile) && NumberUtils.isNumber(rmobile)){
                                    mld.setcName(rname);
                                    mld.setcMobile(rmobile);
                                    list.add(mld);
                                }

                        }

                        // 去除重復
                        list = removeDuplicateWithOrder(list);

                        if (list != null && !list.isEmpty()) {
                            //System.out.println("開始json");

                            //若list不為空,則將其轉換成JSON對象,并存入jsonArray中  
                            JSONArray jsonArray = JSONArray.fromObject(list);   
                            //下面就是把存有查詢結果的JSON對象返給頁面  
                            //System.out.println(jsonArray);
                            out.println("<script type=\"text/javascript\">parent.rtnList("+jsonArray+");</script>");
                        }
                        out.println(showMsg("共成功導入" + String.valueOf(list.size())+"個手機號碼!"));                     

                }
                    out.flush();
                    out.close();
                    delFile(u_name);

                } catch (Exception e) {
                    out.println(showMsg("電話號碼文件解析出錯!"));
                    delFile(u_name);
                    logger.error(e.getMessage(),e);
                }
            } catch (Exception e) {
                out.println(showMsg("電話號碼文件導入出現異常!"));
                delFile(u_name);
                logger.error(e.getMessage(),e);
            }

        }

    }
}
private void checkPath(String filepath) throws Exception {
        File file = new File(filepath);
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
    }


 本文由用戶 GiseleGrang 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!