兩種java檔案上傳執行個體講解_java

來源:互聯網
上載者:User

本文通過兩種檔案上傳執行個體進行比較,協助大家更好的學習java檔案上傳功能,具體內容如下

1. Java附件上傳代碼    

@Controllerpublic class UploadFile extends BaseJsonController{   /**   * 附件上傳   *    * @param request   * @param creativeFile   * @param response   * @return   */  @RequestMapping(value = "/upload/uploadFile.json")  public void uploadFile(HttpServletRequest request,HttpServletResponse response) {    /**     * 1、為保證伺服器安全,上傳檔案應該放在外界無法直接存取的目錄下,比如放於WEB-INF目錄下。     * 2、為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔案名稱。     * 3、為防止一個目錄下面出現太多檔案,要使用hash演算法打散儲存。     * 4、要限制上傳檔案的最大值。     * 5、要限制上傳檔案的類型,在收到上傳檔案名稱時,判斷尾碼名是否合法。     */     //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接存取,保證上傳檔案的安全    String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");    //上傳時產生的臨時檔案儲存目錄    String tempPath = request.getSession().getServletContext().getRealPath("/WEB-INF/temp");    File tmpFile = new File(tempPath);    if (!tmpFile.exists()) {      //建立臨時目錄      tmpFile.mkdirs();    }     //訊息提示    JSONArray arr = new JSONArray();    Map<String,Object> map = null;         InputStream in = null;    FileOutputStream out = null;    try{      //使用Apache檔案上傳組件處理檔案上傳步驟:      //1、建立一個DiskFileItemFactory工廠      DiskFileItemFactory factory = new DiskFileItemFactory();      //設定工廠的緩衝區的大小,當上傳的檔案大小超過緩衝區的大小時,就會產生一個臨時檔案存放到指定的臨時目錄當中。      factory.setSizeThreshold(1024*100);//設定緩衝區的大小為100KB,如果不指定,那麼緩衝區的大小預設是10KB      //設定上傳時產生的臨時檔案的儲存目錄      factory.setRepository(tmpFile);      //2、建立一個檔案上傳解析器      ServletFileUpload upload = new ServletFileUpload(factory);      //監聽檔案上傳進度      upload.setProgressListener(new ProgressListener(){        public void update(long pBytesRead, long pContentLength, int arg2) {          System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead);        }      });      //解決上傳檔案名稱的中文亂碼      upload.setHeaderEncoding("UTF-8");       //3、判斷提交上來的資料是否是上傳表單的資料      if(!ServletFileUpload.isMultipartContent(request)){        //按照傳統方式擷取資料        return;      }       //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是20MB      upload.setFileSizeMax(1024*1024*20);      //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為40MB      upload.setSizeMax(1024*1024*40);      //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項      @SuppressWarnings("unchecked")      List<FileItem> list = upload.parseRequest(request);       for(FileItem item : list){        //如果fileitem中封裝的是普通輸入項的資料        if(item.isFormField()){          String name = item.getFieldName();          //解決普通輸入項的資料的中文亂碼問題          String value = item.getString("UTF-8");          //value = new String(value.getBytes("iso8859-1"),"UTF-8");          System.out.println(name + "=" + value);        }else{//如果fileitem中封裝的是上傳檔案          //得到上傳的檔案名稱,          String filename = item.getName();          if(filename==null || filename.trim().equals("")){            continue;          }          //注意:不同的瀏覽器提交的檔案名稱是不一樣的,有些瀏覽器提交上來的檔案名稱是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔案名稱,如:1.txt          //處理擷取到的上傳檔案的檔案名稱的路徑部分,只保留檔案名稱部分          filename = filename.substring(filename.lastIndexOf("\\")+1);          //得到上傳檔案的副檔名          String fileExtName = filename.substring(filename.lastIndexOf(".")+1);          //如果需要限制上傳的檔案類型,那麼可以通過檔案的副檔名來判斷上傳的檔案類型是否合法          if(StringUtils.equals(fileExtName, "rar") || StringUtils.equals(fileExtName, "zip")){            throw new BizException("","禁止上傳壓縮檔!");          }                     /*************/          //擷取item中的上傳檔案的輸入資料流          in = item.getInputStream();          /************/           //得到檔案儲存的名稱          String saveFilename = makeFileName(filename);          //得到檔案的儲存目錄          String realSavePath = makePath(saveFilename, savePath);          //建立一個檔案輸出資料流          out = new FileOutputStream(realSavePath + "\\" + saveFilename);          //建立一個緩衝區          byte buffer[] = new byte[1024];          //判斷輸入資料流中的資料是否已經讀完的標識                 int len = 0;          //迴圈將輸入資料流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料          while((len=in.read(buffer))>0){            //使用FileOutputStream輸出資料流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中            out.write(buffer, 0, len);          }          //關閉輸入資料流          in.close();          //關閉輸出資料流          out.close();                 //刪除處理檔案上傳時產生的臨時檔案                  item.delete();                 map = new HashMap<String,Object>();          map.put("saveFilename", saveFilename);          map.put("realSavePath", realSavePath);          arr.add(map);        }      }      returnSuccessJSON("上傳成功", arr, response);     }catch (FileUploadBase.FileSizeLimitExceededException e) {      e.printStackTrace();      returnFailJSON(e.getMessage(), "單個檔案超出最大值!!!", response);     }catch (FileUploadBase.SizeLimitExceededException e) {      e.printStackTrace();      returnFailJSON(e.getMessage(), "上傳檔案的總的大小超出限制的最大值!!!", response); arr.toString();    }catch (Exception e) {      e.printStackTrace();      returnFailJSON(e.getMessage(), "檔案上傳失敗!", response); arr.toString();    }finally{      try {       //關閉輸入資料流        in.close();       //關閉輸出資料流        out.close();      } catch (IOException e) {               }    }  }   /**   * @Method: makeFileName   * @Description: 產生上傳檔案的檔案名稱,檔案名稱以:uuid+"_"+檔案的原始名稱   * @Anthor:xuwentao   * @param filename 檔案的原始名稱   * @return uuid+"_"+檔案的原始名稱   */  private String makeFileName(String filename){ //2.jpg    //為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔案名稱    return UUID.randomUUID().toString() + "_" + filename;  }    /**   * 為防止一個目錄下面出現太多檔案,要使用hash演算法打散儲存   * @Method: makePath   * @Description:    * @Anthor:xuwentao   *   * @param filename 檔案名稱,要根據檔案名稱產生儲存目錄   * @param savePath 檔案儲存體路徑   * @return 新的儲存目錄   */  private String makePath(String filename,String savePath){    //得到檔案名稱的hashCode的值,得到的就是filename這個字串對象在記憶體中的地址    int hashcode = filename.hashCode();    int dir1 = hashcode&0xf; //0--15    int dir2 = (hashcode&0xf0)>>4; //0-15    //構造新的儲存目錄    String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5    //File既可以代表檔案也可以代表目錄      File file = new File(dir);    //如果目錄不存在    if(!file.exists()){      //建立目錄      file.mkdirs();    }    return dir;  }}

2. Java上傳簡曆代碼

/** * 上傳簡曆 * 1--建立檔案失敗 2--異常 3--上傳失敗  4--檔案未擷取 5--檔案未刪除  6--請上傳word、excel、ppt、pdf檔案 */ /*路徑分隔字元:用於自適應作業系統*/ private static final String FILE_SEPARATOR = System.getProperties()   .getProperty("file.separator");  /** * 上傳檔案 *  * @param FileIO * @param oldContractURL * @param request * @return 返迴文件地址(相對位址,非絕對位址) */ @Override public String upload(MultipartFile FileIO, String oldContractURL, HttpServletRequest request) {    String uploadUrl = request.getSession().getServletContext().getRealPath("files");   //刪除檔案及檔案夾   if (oldContractURL != null) {     String oldDirectory = oldContractURL.substring(5,       oldContractURL.lastIndexOf(FILE_SEPARATOR));     File file = new File(uploadUrl + oldDirectory);     boolean flag = deleteDir(file);     if (!flag) {       logger.error("舊檔案刪除失敗");       return "5";     }   }   //上傳新的簡曆檔案   long now = System.currentTimeMillis();   uploadUrl = uploadUrl + FILE_SEPARATOR + now + FILE_SEPARATOR;   String resumeName = "";   if (!FileIO.isEmpty()) {     resumeName = StringUtils.deleteWhitespace(FileIO.getOriginalFilename());     //判斷檔案尾碼     /*String suffix = resumeName.substring(resumeName.lastIndexOf("."), resumeName.length())       .toLowerCase();     if (!".doc".equals(suffix) && !".docx".equals(suffix) && !".xls".equals(suffix)       && !".xlsx".equals(suffix) && !".ppt".equals(suffix) && !".pptx".equals(suffix)       && !".pdf".equals(suffix)) {       logger.error("不是word、excel、ppt、pdf檔案");       return "6";     }*/   } else {     logger.error("檔案未擷取");     return "4";   }    File dir = new File(uploadUrl);   if (!dir.exists()) {     dir.mkdirs();   }   File targetFile = new File(uploadUrl + resumeName);   if (!targetFile.exists()) {     try {       targetFile.createNewFile();     } catch (IOException e) {       logger.error("檔案建立失敗", e);       return "1";     }   }   try {     FileIO.transferTo(targetFile);   } catch (IllegalStateException e) {     logger.error("語句異常", e);     return "2";   } catch (IOException e) {     logger.error("上傳失敗", e);     return "3";   }   return FILE_SEPARATOR + "files" + FILE_SEPARATOR + now + FILE_SEPARATOR + resumeName; }  /** * 遞迴刪除目錄下的所有檔案及子目錄下所有檔案 * @param dir 將要刪除的檔案目錄 * @return boolean Returns "true" if all deletions were successful. *         If a deletion fails, the method stops attempting to *         delete and returns "false". */ public boolean deleteDir(File dir) {   if (dir.isDirectory()) {     String[] children = dir.list();     //遞迴刪除目錄中的子目錄下     for (int i = 0; i < children.length; i++) {       boolean success = deleteDir(new File(dir, children[i]));       if (!success) {         return false;       }     }   }   // 目錄此時為空白,可以刪除   return dir.delete(); }

以上就是本文的全部內容,希望對大家的學習有所協助,掌握java檔案上傳的技巧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.