Drew H
Drew H

Reputation: 4739

HttpServletResponse response: Ask user to download file instead of auto downloading

This is my download code. It just starts downloading the file without asking user. I've searched multiple forums and nothing seems to work. This is code is in a backing bean attached to a commandButton.

public void doDownloadFile() {   

    PrintWriter out = null;

    try {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();   
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=test.csv");
        out = response.getWriter();
        CSVWriter writer = new CSVWriter(out);

        List<String[]> stringList = new ArrayList<String[]>();

        for (User user : userList) {

            String[] string = {user.getEmail(), user.getName(), user.getPassword()};
            stringList.add(string);
        }

        writer.writeAll(stringList);
        out.flush();

    } catch (IOException ex) {
        Logger.getLogger(ViewLines.class.getName()).log(Level.SEVERE, null, ex);     
    } finally {
        out.close();
    }
}

Upvotes: 1

Views: 4170

Answers (2)

Neil
Neil

Reputation: 5780

The behavior of what to do with a download is 100% local, meaning it's the browser, not you, that determines what to do in that case. Whether the user's browser just dumps the file in a download folder or allows him to save it to a particular spot is entirely up to the browser.

Not much to be done.

Upvotes: 2

Raghuram
Raghuram

Reputation: 52645

This is most likely due to the fact your browser is configured to download files of these types without prompt. The code has nothing to do with it.

Upvotes: 2

Related Questions