4

I am trying to create a temp file and generate a file name and then save a multipart file. I am using Spring Boot and the following code is working in local. But in heroku or docker it is throwing FileNotFoundException; So how to create a temp directory and save a file inside that temp directory in docker/heroku? Or what is the best way to save multipart file to temp folder in server? Anybody can help me? Thanks in advance.

File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");

   if (!tempDirectory.exists()) {
       tempDirectory.mkdir();
   }

String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.pdf").getAbsolutePath();
Abraham Arnold
  • 301
  • 4
  • 20
  • Could it be something to do with the file not actually being created? perhaps file creation issue? also, could a file be being blocked from created with the ".exe" extension? – Chucky May 02 '21 at 05:21
  • I'm confused about your `temp.exe`. The latest Heroku stack is Ubuntu 20. Linux does not understand `.exe` files. Try to print out the `tempDirectory` and see if the path exists or you can adjust your `Procfile` and add `-Djava.io.tmpdir=\tmp`. Change `mkdir()` to `mkdirs()` so it also creates parent directories if they are missing.You've shown code how you get the `filePath` String but how are you creating the file on your system. It worked locally so there should be code for it. – Tin Nguyen May 03 '21 at 07:42

1 Answers1

1
 File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
        if(tempDirectory.exists()){
            System.out.println("something");
        }else{
            tempDirectory.mkdirs();
        }

        File file = new File(tempDirectory.getAbsolutePath()+"/abcd.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        String file2= new File(tempDirectory.getAbsolutePath()+"/something.txt").getAbsolutePath();


        System.out.println(file2);

Works totally fine at my end. The only problem you might be having is

String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.exe").getAbsolutePath();

This doesn't create the file in the temp directory you have created. It just returns the absolute path if it was to be saved in the directory mentioned. This might be the reason you are getting not found error. Try actually saving by using

file.transferTo(wherefileneedstobesavedlocation);
Bishal Gautam
  • 380
  • 3
  • 16