2017-06-14 93 views
0

我上傳文件到一個文件夾,我給文件名稱爲「1.jpg」,所以當我上傳一個新文件時,它會覆蓋現有文件,所以我可以給一個隨機文件名對此我上傳如何給隨機文件名稱到文件,我正在上傳?

我上傳的代碼的文件就在這裏

@RequestMapping(value = "/event/uploadFile",headers=("content-type=multipart/*"), method = RequestMethod.POST,consumes ={"application/x-www-form-urlencoded"}) 
    //String quote_upload=C:\fakepath\images.jpg 
    public @ResponseBody 
    String uploadFileHandler(

      @RequestParam MultipartFile file) { 
     System.out.println("Creating the directory to store file"); 

     if (!file.isEmpty()) { 
      try { 
       byte[] bytes = file.getBytes(); 


       // Creating the directory to store file 
       String rootPath = System.getProperty("catalina.home"); 
       File dir = new File(rootPath + File.separator + "tmpFiles"); 
       if (!dir.exists()) 
        dir.mkdirs(); 

       // Create the file on server 
       File serverFile = new File(dir.getAbsolutePath() 
         + File.separator+"1.jpg"); 
       BufferedOutputStream stream = new BufferedOutputStream(
         new FileOutputStream(serverFile)); 
       stream.write(bytes); 
       stream.close(); 

       System.out.println("************Server File Location=" 
         + serverFile.getAbsolutePath()); 

       //return "You successfully uploaded file=" + name; 
      } catch (Exception e) { 
       System.out.println("************failes"+ e.getMessage()); 
       //return "You failed to upload " + name + " => " + e.getMessage(); 
      } 
      //return "You failed to upload " + name 
        //+ " because the file was empty."; 
     } 
     System.out.println("hello"); 
     return "hello"; 
    } 
+0

一種選擇是追加當前時間(最多秒),並從'隨機數發生器Random'。 – tsolakp

+0

您可以使用'java.util.UUID.randomUUID()'方法爲'serverFile'創建唯一名稱 –

回答

1

如果你不希望的名稱有任何合理的順序,我可能會用UUID去。像這樣的東西應該這樣做:

String filename = UUID.randomUUID().toString(); 

如果你擔心的UUID的唯一性,看看this thread。總之,你是非常不可能得到兩個相同的ID。

2

您可以使用

Calendar.getInstance().getTimeInMillis(); 

它將返回的時間以毫秒爲單位。
如果你不確定這個附加了一些隨機數。

1
  1. 隨機生成一個名稱爲您新上傳的文件

    String fileName = UUID.randomUUID().toString()+YOUR_FILE_EXTENSION;

  2. 檢查文件是否在目錄中存在您上傳

    if(serverFile.exists())

  3. 如果文件中存在啓動再從第1步開始,直到獲得服務器中不存在的文件名。

注:這不是最佳的解決方案,但將滿足您的要求。

1

您可以使用:

File.createTempFile(String prefix, String suffix, File directory) 

由於JavaDoc狀態:

創建指定目錄中的新的空文件,使用給定的前綴和後綴字符串生成其名稱。如果此方法成功返回則保證:

  1. 由返回的抽象路徑名此方法之前不存在表示的文件被調用,並
  2. 無論這種方法也不是任何變體將返回相同在虛擬機的當前調用中再次提取抽象路徑名。
0

你可以簡單地得到一個隨機的大整數,給你的文件名,例如:

String fileExtension = ".jpg"; 
String fileName = Integer.toString(new Random().nextInt(1000000000)) + fileExtension; 
相關問題