1

I am uploading a file to a folder , i had given the file name as "1.jpg" , so when i am uploading a new file it will overwrite the existing one, So How i can give a random file name to the file which i am uploading

MY UPLOAD CODE IS HERE

@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";
    }
2
  • One option is to append current time (up to seconds) and random number generator from Random. Commented Jun 14, 2017 at 4:57
  • 1
    You can use java.util.UUID.randomUUID() method to create unique name for serverFile Commented Jun 14, 2017 at 5:10

5 Answers 5

5

If you do not expect the names to have any sensible order, I would probably go with UUID. Something like this should do it:

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

If you're worried about uniqueness of the UUID, have a look at this thread. In short, you are extremely unlikely to ever get two ids that are the same.

Sign up to request clarification or add additional context in comments.

Comments

3
  1. Generate a Random Name for your newly uploaded file

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

  2. Check if File exist in the directory you are uploading

    if(serverFile.exists())

  3. If File Exist start again from step 1 until you get a file name which is not present in the server.

Note: This is not the optimal solution but will fulfill your requirement.

Comments

2

You can use

Calendar.getInstance().getTimeInMillis();  

It will return the time in milliseconds.
If you are not sure about this append some random number to it.

Comments

2

You may use:

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

As the JavaDoc states:

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:

  1. The file denoted by the returned abstract pathname did not exist before this method was invoked, and
  2. Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

Comments

-1

You can simply get a random large integer and give your file that name, like so:

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

1 Comment

This can lead to duplicates.. nextInt can return duplicate values..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.