本问题已经有最佳答案,请猛点这里访问。
我正在将一个文件上载到一个文件夹中,我将文件名命名为"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的随机数生成器。
可以使用java.util.UUID.randomUUID()方法为serverFile创建唯一的名称。
您可以使用:
File.createTempFile(String prefix, String suffix, File directory)
正如JavaDoc所说:
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
The file denoted by the returned abstract pathname did not exist before this method was invoked, and
Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
你可以使用
Calendar.getInstance().getTimeInMillis();
它将返回以毫秒为单位的时间。如果您不确定这一点,请在上面附加一些随机数。
如果你不希望这些名字有任何合理的顺序,我可能会选择UUID。像这样的事情应该可以做到:
String filename = UUID.randomUUID().toString();
如果您担心uuid的独特性,请看一下这个线程。简而言之,您不太可能获得两个相同的ID。
为新上载的文件生成随机名称
String fileName = UUID.randomUUID().toString()+YOUR_FILE_EXTENSION;
检查正在上载的目录中是否存在文件
if(serverFile.exists())
如果文件存在,请从步骤1重新开始,直到获得服务器中不存在的文件名。
注意:这不是最佳解决方案,但会满足您的要求。
您可以简单地得到一个随机的大整数,并给您的文件命名,如下所示:
String fileExtension =".jpg";
String fileName = Integer.toString(new Random().nextInt(1000000000)) + fileExtension;