1

i Have a problem with download file by jquery.

I have a post function that send request in the java code.

I return the file but this doesn't download.

Input

 <input type="button" id="export-csv" value="Export result in CSV"/> 

Html-jquery Code

$( "#export-csv" ).click(function( ) { var request=$.ajax({ method: "POST", url: 'user/writeCsv', data: $( "#search-form" ).serialize(), dataType: "text/csv" }).done(function(data) { window.location.href = (data); }); // $.post( "user/writeCsvToReturn", $( "#search-form" ).serialize()) }); 

Java code

@RequestMapping(value="/user/writeCsv",method=RequestMethod.POST) public FileWriter writeCSVFile(HttpServletResponse response,ServerSearchCommand ssc, Model model, BindingResult result) throws IOException { FileWriter fileWriter= new FileWriter("/tmp/searchcsv.csv"); fileWriter.flush(); //WRITE DATA FILE fileWriter.close(); return fileWriter; } 
1
  • Thanks very much people ! Commented Mar 31, 2016 at 8:46

2 Answers 2

1

If you don't want to submit form , you can have this work around write the file in response object in get request:-

@RequestMapping(value="/user/writeCsv",method=RequestMethod.Get) public void writeCSVFile(HttpServletResponse response,ServerSearchCommand ssc, Model model, BindingResult result) throws IOException { OutputStream outStream = response.getOutputStream(); // Write data to this outStream outStream.close(); } 

On front end , side append file to iFrame and make iFrame stye = display:none :-

 var url = contextPath + "/user/writeCsv"; var hiddenIFrameID = 'frameid', iframe = document.getElementById(hiddenIFrameID); if (iframe === null) { iframe = document.createElement('iframe'); iframe.id = hiddenIFrameID; iframe.style.display = 'none'; document.body.appendChild(iframe); } iframe.src = url; 
Sign up to request clarification or add additional context in comments.

Comments

0

Simply you cannot. With Ajax you cannot download a file due to security reasons. All you can do is a submit a form request.

2 Comments

Hi :) how can i do ?
@Marco ajax doesnot support it directly , but there are work around

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.