1. 程式人生 > >多檔案上傳中重名檔案問題,日期轉特殊字串

多檔案上傳中重名檔案問題,日期轉特殊字串

 Today,牛刀小試了一下,在多檔案上傳的時候需要解決檔案重名的問題(由於上傳的路徑是固定的,所以不能實現重名的檔案的上傳)。

解決辦法:

  日期轉換為字串(可以保證唯一)加到檔名中,實現同一資料夾下都是唯一的檔案

相關知識點:

日期格式化:SimpleDateFormat
字串拼接:+ 、 split( )方法
多檔案變數(MultipartFile)transferTo(serverFile )

相關程式碼片:

// 程式碼片一
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"
); String dt = sdf.format(new Date());
// 程式碼片二
String[] str = oldFilename.split("\\.");

String newFilename = str[0]
        + new SimpleDateFormat("yyMMddHHmmss").format(new Date()) + "."
        + str[1];
// 整體測試程式碼片
import java.io.File;
import java.io.IOException;
import java.text.ParseException
; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) throws ParseException, IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); String dt = sdf.format(new Date()); File file = new File("C:\\Users\\K\\Desktop\\測試.txt"
); String absoPath = file.getAbsolutePath(); String oldFilename = file.getName(); System.out.println(oldFilename); String[] str = oldFilename.split("\\."); String newFilename = str[0] + dt + "." + str[1]; absoPath = absoPath.substring(0, absoPath.length() - oldFilename.length()) + newFilename; System.out.println(absoPath); } }
/** 程式碼片三
  * file File型別變數
  * serverFile MultipartFile型別變數
  * 
  */

// 構造方法完成File變數(serverFile )初始化,新增路徑資訊
serverFile = new File(Global.getConfig("upload.path") + newName); 

// 將收到的檔案轉移到給定的目標檔案
file.transferTo(serverFile); 

PS:

 如果對transferTo()方法還有疑問,可以到org.springframework.web.multipart 包下進一步檢視相關注釋,或者留言交流