|
Programming -
java
|
|
The client side codes cannot write a file on the client computer, so particularly in web-programming, we need to create a servlet which will send the file to be saved as a downloadable file to the client side. This will envoke the "SAVE AS" dialog of the browser making it possible to save the file in desired name.
In client side first POST a request with the comma-seperated string as a request string, then envoke the GET method with code like
Window.open(ServerAddress +"/CsvFile", "123", "");
| Server Side Source Code |
package package.server;
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
/** * This class is used to export files as CSVformat. As client side code cannot * write a file, we have to rely on the server side code like this to export a * file and make it possible to user to save data in desired format. Rightnow * the only supported format is CSV. * * @author NischalDahal * */ public class CsvFile extends HttpServlet {
private static final long serialVersionUID = 1L; String data = "";
public void doPost(HttpServletRequest request, HttpServletResponse response) { try { InputStream in = request.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); data = sb.toString(); System.out.println("test3\n" + data); doGet(request, response);
} catch (Exception ex) { ex.printStackTrace(); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) { ServletOutputStream out;
try { out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
response.setHeader("Content-type", "application/csv"); response.setHeader("Content-disposition", "attachment; filename=" + "Report.csv"); for (int i = 0; i < data.length(); i++) bos.write(data.charAt(i)); bos.flush();
bos.close(); out.println(data); } catch (IOException e) { e.printStackTrace(); } } }
}
|
|
|
|
Last Updated on Sunday, 28 March 2010 11:02 |