How To Give A Random File Name To File , Which i am Uploading?
本问题已经有最佳答案,请猛点这里访问。
我正在将一个文件上载到一个文件夹中,我将文件名命名为"1.jpg",因此当我上载一个新文件时,它将覆盖现有文件,所以我如何给上传的文件随机命名
我的上传代码在这里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | @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"; } |
您可以使用:
正如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.
你可以使用
1 |
它将返回以毫秒为单位的时间。如果您不确定这一点,请在上面附加一些随机数。
如果你不希望这些名字有任何合理的顺序,我可能会选择
1 |
如果您担心uuid的独特性,请看一下这个线程。简而言之,您不太可能获得两个相同的ID。
为新上载的文件生成随机名称
检查正在上载的目录中是否存在文件
如果文件存在,请从步骤1重新开始,直到获得服务器中不存在的文件名。
注意:这不是最佳解决方案,但会满足您的要求。
您可以简单地得到一个随机的大整数,并给您的文件命名,如下所示:
1 2 |