Search code examples
javajsppathfilewriter

FileWriter to write to user desktop in Java, rather than server desktop


As part of a search application, I want the user to be able to download a report showing the results in a CSV file. I have the following method:

public void downloadCustomerResults(String customer) {
        String output = "";
        output += produceCustomerID(customer);
        output += produceCustomerAddress(customer);
        output += produceCustomerContactDetails(customer);
        output += produceOrderHeader(customer);
        output += producePayments(customer);

        //  Writes to server desktop, not user desktop.
        try {
            Writer fileWriter = new FileWriter("C:\\Users\\username\\Desktop\\SAR" + customer + "C.csv");
            fileWriter.write(output);
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This downloads the file to the desktop of the machine running the server, not the user's desktop (accessing the app via JSP's on Tomcat). How would I change the file path string to make this download to the users' desktop? Or would I have to pass the file to the JSP for the user to download via their browser?

Thanks.


Solution

  • So the answer I found was to use the JavaScript package FileSaver.js. This accepts a blob created from a string, and then saves it with a filename of your choice to the browsers preferred download folder.

    I managed to pass the string from Java to JavaScript, and then pass it through FileSaver.js in the .JSP page.