Skip to content

Instantly share code, notes, and snippets.

@americos
Created January 31, 2013 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save americos/4683962 to your computer and use it in GitHub Desktop.
Save americos/4683962 to your computer and use it in GitHub Desktop.
Sample of Downloading data a .csv using a .jsp and a Form Post
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#csv_form").submit(function(event) {
event.preventDefault();
var csv_data = jQuery("#csv_data").val();
var file_name = jQuery("#file_name").val();
jQuery.post( "csv.jsp", {
csv_data: csv_data,
file_name: file_name
})
})
$("#xx").click(function(){
var hidden_form =[
'<form action="csv.jsp" method="POST">',
'<input type="hidden" name="csv_data" value="AA,BBB,CCCC"></input>',
'<input type="hidden" name="file_name" value="some.csv"></input>',
'</form>'
].join("");
$(hidden_form).submit();
console.log("done")
})
})
</script>
</head>
<body >
<h2>Type the data you want to save as csv:</h2>
<form name="csv_form" method="post" action="csv.jsp">
<textarea name="csv_data"cols="80" rows="10"></textarea>
<br>
Filename:<input type="text" name="file_name" value="data.csv"/>
<br>
<input type="submit"> </input>
</form>
<h2>Test Simulating a hidden form with jQuery</h2>
<input type="button" value="Using Hidden Form" id="xx"></input>
</body>
</html>
<%@ page import="java.io.*" %>
<%@ page import="java.servlet.*" %>
<%@ page import="java.servlet.http.*" %>
<%
/*
@param: This code expects "csv_data" to contain the data to download as csv
@param: In "file_name" its an optional param for naming the .csv file
*/
String csv_string = request.getParameter("csv_data");
String file_name = request.getParameter("file_name");
if(file_name.length() == 0) file_name = "data.csv";
response.setContentType("application/csv");
response.setHeader("content-disposition","filename="+file_name); // Filename
PrintWriter outx = response.getWriter();
outx.println(csv_string);
outx.flush();
outx.close();
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment