Search code examples
eclipsefileservletsstorageidentifier

Upload Servlet with custom file keys


I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).

Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.

I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.

Any thoughts, suggestions or solutions for my problem?


Solution

  • Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt. Try this:

    filekey= RenameRandom();
     File renamedUploadFile = new File(uploadFolder +  File.separator+ filekey+ fileName);
                    item.write(renamedUploadFile);
    //remember to give the user the filekey
    

    with

     public String RenameRandom()  
    {  
      final int LENGTH = 8;  
      StringBuffer sb = new StringBuffer();  
      for (int x = 0; x < LENGTH; x++)  
      {  
        sb.append((char)((int)(Math.random()*26)+97));  
      }  
      System.out.println(sb.toString());  
      return sb.toString();
    }
    

    To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:

    filekey= request.getParameter("filekey");
    File f = new File(getServletContext().getRealPath("") + File.separator+"data");
        File[] matchingFiles = f.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.startsWith(filekey);
            }
        });    
        String newfilename = matchingFiles[0].getName();
    // now delete or download newfilename