Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Applets Code Examples

Sending a file from Applet to Servlet

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
Sending a file from Applet to Servlet import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import javax.swing.*; public class TestApplet extends JApplet implements ActionListener { JButton jbutton = null; public void init() { jbutton = new JButton("Send file"); jbutton.addActionListener(this); this.getContentPane().add(jbutton); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == jbutton) { try { File file = new File("C:\uma.txt"); FileInputStream in = new FileInputStream(file); byte[] buf=new byte[in.available()]; int bytesread = 0; String toservlet = "http://localhost:8080/servlet/MyServlet"; URL servleturl = new URL(toservlet); URLConnection servletconnection = servleturl.openConnection(); servletconnection.setDoInput(true); servletconnection.setDoOutput(true); servletconnection.setUseCaches(false); servletconnection.setDefaultUseCaches(false); DataOutputStream out=new DataOutputStream(servletconnection.getOutputStream()); while( (bytesread = in.read( buf )) > -1 ) { out.write( buf, 0, bytesread ); } out.flush(); out.close(); in.close(); DataInputStream inputFromClient = new DataInputStream(servletconnection.getInputStream()); //get what you want from servlet //....... inputFromClient.close(); } catch(Exception e) { e.printStackTrace(); } } } } import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) { ServletContext sc = this.getServletContext(); try { String fileName = "uma.txt"; String path = sc.getRealPath(File.separator)+fileName; File yourFile = new File(path); FileOutputStream toFile = new FileOutputStream( yourFile ); DataInputStream fromClient = new DataInputStream( req.getInputStream() ); byte[] buff = new byte[1024]; int cnt = 0; while( (cnt = fromClient.read( buff )) > -1 ) { toFile.write( buff, 0, cnt ); } toFile.flush(); toFile.close(); fromClient.close(); } catch(Exception e) { e.printStackTrace(); } } }