【问题标题】:How To Give A Random File Name To File , Which i am Uploading? [duplicate]如何给我正在上传的文件指定一个随机文件名? [复制]
【发布时间】:2017-11-16 01:39:00
【问题描述】:

我正在将文件上传到文件夹,我已将文件名指定为“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 创建唯一名称

标签: java spring


【解决方案1】:

如果您不希望这些名称有任何合理的顺序,我可能会选择UUID。应该这样做:

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

如果您担心 UUID 的唯一性,请查看 this thread。简而言之,您不太可能得到两个相同的 id。

【讨论】:

    【解决方案2】:

    您可以简单地获取一个随机的大整数并为您的文件命名,如下所示:

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

    【讨论】:

    • 这会导致重复。nextInt 可以返回重复值。。
    【解决方案3】:

    你可以使用:

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

    正如JavaDoc 所说:

    在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。如果此方法成功返回,则保证:

    1. 返回的抽象路径名表示的文件在调用此方法之前不存在,并且
    2. 此方法及其任何变体都不会在虚拟机的当前调用中再次返回相同的抽象路径名。

    【讨论】:

      【解决方案4】:
      1. 为您新上传的文件生成一个随机名称

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

      2. 检查文件是否存在于您要上传的目录中

        if(serverFile.exists())

      3. 如果文件存在,则从步骤 1 重新开始,直到您获得服务器中不存在的文件名。

      注意:这不是最佳解决方案,但会满足您的要求。

      【讨论】:

        【解决方案5】:

        你可以使用

        Calendar.getInstance().getTimeInMillis();  
        

        它将以毫秒为单位返回时间。
        如果您对此不确定,请在其中添加一些随机数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-28
          • 2018-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-26
          • 2020-07-12
          相关资源
          最近更新 更多