Upload from Applet to Servlet

  • Thread starter =?ISO-8859-1?Q?Sascha_M=F6llering?=
  • Start date
?

=?ISO-8859-1?Q?Sascha_M=F6llering?=

Hi,

I want to upload a file (as a byte-array) and several parameters
(filename etc.) from an applet to a servlet. I tried using the
HttpMessage-Class from the COS-Classes, but that does not work (Missing
boundary ..) as I expected.
Does anybody have working sample code?


Thank you in advance,

Sascha
 
I

Ike

Use FileOutputStreams to send arrays of serializable Objects to
HTTPServlet.service(). Here is a pared down version of how I do it:

public class YourServlet extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {

ObjectInputStream inputFromApplet = new
ObjectInputStream(request.getInputStream());
Object connArray[] = (Object[])inputFromApplet.readObject();
inputFromApplet.close();

//now, in my servlet, if I am, for example, looking for a string
in element 3 of the array of objects passed:
(String)connArray[3]
//just cast to whatever it is when sent:(sometimes, I use
element 0 as an ArrayList of the types that follow!
((ArrayList)connArray[0])
(Double)connArray
// see?

//now, you can even send things back to the applet this way
// send objects back to applet
ObjectOutputStream outputToApplet = new
ObjectOutputStream(response.getOutputStream());
outputToApplet.writeObject(/*some serializable object such as
Object[] as we sent to the servlet*/);
outputToApplet.flush();
outputToApplet.close();
}catch(Exception e){}
}
}

//and in your applet, call the servlet and pass it objects:

try {
String host = applet.getDocumentBase().getHost();
URL servletURL = null;
String servletURLstring;// eg "/servlets/YourServlet"
servletURL = new URL("http://" + host + servletURLstring);
System.out.println("servlet invoked:" + servletURL);
URLConnection uc = servletURL.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setRequestProperty("Content-type","application/octet-stream");

ObjectOutputStream objOut = new
ObjectOutputStream(uc.getOutputStream());
int sz=5; //telling it the size in advance

Object conArray[] = new Object[sz];
conArray[0] = //whatever objects I
conArray[1] = //wish to send...

objOut.writeObject(conArray);
objOut.flush();
objOut.close();

// get objects from servlet
ObjectInputStream objIn = new ObjectInputStream (uc.getInputStream());
String returnString = (String)objIn.readObject();
objIn.close();

catch (Exception e) {
e.printStackTrace();
}
//Good luck, pls advise that you got this to work. -Ike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top