-1

I have a requirement to download a csv file from a Spring MVC application. I have the data which I need to include in the file. I need to create a file on the fly in the browser session and download it to the user system. I tried doing the solution as mentioned here: Downloading a file from spring controllers

I was unable to produce the csv and it is looking for a file on the server.

What I have done so far:

Client Side Call:

$.ajax({
        type: "GET",
        url:"${ctx}/emp/getAttendance?empId=" + emp +"&fileName=" + file,
        success: function (data) {
            $('#result_loading').hide();
        }
    });

Server Side:

    String path = req.getServletContext().getRealPath("");
    File file = new File(path + "/" + fileName);
    file.createNewFile();
    FileInputStream inputStream = new FileInputStream(file);
    resp.setContentType("application/pdf");
    resp.setHeader("content-disposition;","attachment;filename=\"download.pdf\"");
    OutputStream outputStream = resp.getOutputStream();
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();

I need the Ajax call to download the file. I don't see even an empty file downloaded.

Can someone help me with this on where I am doing wrong.

Community
  • 1
  • 1
Sri
  • 573
  • 2
  • 6
  • 20

1 Answers1

1

You can use the FileSystemResource class from the spring framework the class exists in the location

org.springframework.core.io.FileSystemResource

Write your data onto a file (on the physical server) by creating a csv file using the java.io.File Class and then pass the value of the file object to the constructor

FileSystemResource(File file)

and return this to the browser, the browser will automatically open up a download window once the url is loaded.

Delete the file once the file system resource is initialized, and you would be as good as you never created the file.

Aman J
  • 452
  • 4
  • 15