1

I have uploaded a file from my system, I have converted the file in bytes. Now I want to save that file at server. How can I do this. I have searched through the internet but found nothing. Is there any solution of this problem? I am uploading file using JSP.

Fahad Murtaza
  • 256
  • 2
  • 9
  • 18

1 Answers1

1

If you are talking about UploadedFile, here is how I achieved this after a huge internet search:

/**
 * Save uploaded file to server
 * @param path Location of the server to save file
 * @param uploadedFile Current uploaded file
 */
public static void saveUploadedFile(String path, UploadedFile uploadedFile) {
    try {
        //First, Generate file to make directories
        String savedFileName = path + "/" + uploadedFile.getFileName();
        File fileToSave = new File(savedFileName);
        fileToSave.getParentFile().mkdirs();
        fileToSave.delete();
        //Generate path file to copy file
        Path folder = Paths.get(savedFileName);
        Path fileToSavePath = Files.createFile(folder);
        //Copy file to server
        InputStream input = uploadedFile.getInputstream();
        Files.copy(input, fileToSavePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {

    }
}
Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61