我上傳文件到一個文件夾,我給文件名稱爲「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";
}
一種選擇是追加當前時間(最多秒),並從'隨機數發生器Random'。 – tsolakp
您可以使用'java.util.UUID.randomUUID()'方法爲'serverFile'創建唯一名稱 –