wood burning stoves 2.0*
The moose likes Servlets and the fly likes connect to a UploadServlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Servlets
Bookmark "connect to a UploadServlet" Watch "connect to a UploadServlet" New topic

connect to a UploadServlet

Holger Prause
Ranch Hand

Joined: Oct 09, 2000
Posts: 47
On the Server-side theres a Servlet that does a FileUpload.
(I downloaded a multi-part request handler which parses an enctype of multipart that file-uploading requires at www.servlets.com.)
With my webbrowser everything is working fine.Now i want my wwing client to connect to this servlel and send a File to it.
I use the Classes URL and URLConnectio to connect to my Servlet.
I used my Webbrowser to do a Upload and printed the HeaderInformation out.
Headername: Content-type
Headervalue: multipart/form-data; boundary=---------------------------165134971149500733551365216

Ok now i see what the Servlet needs.My only Problem is -what is the boundary and where do i get it from ?I downloaded the same File 2 times and the boundary changed - so it cant be the Filesize - right?
Thx for your help,

Danny Mui
Ranch Hand

Joined: Dec 14, 2000
Posts: 42
I think you make up the boundary....all you have to do is make sure you encode the body with the said boundary you specify in the header.
Holger Prause
Ranch Hand

Joined: Oct 09, 2000
Posts: 47

>I think you make up the boundary....all you have to do is make >sure you encode the body with the said boundary you specify in >the header.

To set the attributes i use con.setRequestProperty("key,value");
do i have to set the boundary after ever HeaderField?

Holger Prause
Ranch Hand

Joined: Oct 09, 2000
Posts: 47
Heres the Solution
public void sendFileToServer(File file) throws IOException {
//get the UserDirectory from the Session Servlet
StreamParser parser = new StreamParser(con.getInputStream());
String result = parser.getUserDirectory();
connectToServer(new URL("ServletURL?Directory="+result));
String boundary="---------------------------7d021a37605f0";
HttpURLConnection conn = (HttpURLConnection)con ;
conn.setDoOutput( true );
conn.setDoInput ( true );
conn.setRequestProperty( "Content-Type", "multipart/form-data; boundary=" + boundary );
PrintStream outStream = new PrintStream(
conn.getOutputStream() );
String streamSend = "--" + boundary + "\r\n";
//form file input
streamSend += "Content-Disposition: form-data; name=\"filename\"; filename=\""+file.getAbsolutePath()+"\"\r\n";
streamSend += "\r\n";
String tmp;
//send the FileStream here
reader = new BufferedReader(new FileReader(file));
while( (tmp = reader.readLine()) != null) {
streamSend += tmp+"\r\n";
streamSend += "--" + boundary + "\r\n";
outStream.print( streamSend );
//get the Response from the Servlet
StreamWriter writer = new StreamWriter(con.getInputStream());
writer.writeToDisk(new File("/home/hp/logs/uploaded.txt"));
Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
I am also facing the problem while uploading the file to server. It's corrupted. I am using Oreilley's classes. Can you please where u got the method "ConnectToServer".
Can you please help me to resolve this corrupt while uploading the file to server. If possible can you send the code to Upload the file.

Regards,<BR>V. Kishan Kumar

Joined: Jun 21, 2005
Posts: 3
public void run() {
URL url = null;
URLConnection urlConn = null;
DataOutputStream dOut = null;
BufferedReader bInp = null;
url = new URL(uploadURL);
// Setting up the connection for upload.
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
String boundary = "-----------------------------" + getRandomString();
"multipart/form-data; boundary=" +
boundary.substring(2, boundary.length()));
String CRLF = "\r\n";

// Retrieve OutputStream For upload (Post).
dOut = new DataOutputStream(urlConn.getOutputStream());

// Actual Uploading part.
StringBuffer sb;
File f;
uploadedLength = 0;
for(int i=0; i < aTotalFiles.length && !stop; i++){
f = aTotalFiles[i];
sb = new StringBuffer();
// Line 1.
// Line 2.
sb.append("Content-Disposition: form-data; name=\"File");sb.append(i);
sb.append("\"; filename=\"");sb.append(f.toString());
// Line 3 & Empty Line 4.
sb.append("Content-Type: application/octet-stream");
// Write to Server the 4 Lines, a File and the CRLF.
// Telling the Server we have Finished.
dOut.flush ();
if(!stop) progress.setString("File(s) uploaded. Wait for server response!");

// Reading input from Server.
// NOTE: You have to call getInputStream AFTER you have posted all
// your files. Anything you try to write to the server after calling the
// getInputStream will be lost.
// PROBLEM: You will only find out the status of the server (server/page
// is reachable/exists) after getInputStream. It would be very bad if
// we spend all our time writing to it then find out it was down or
// page doesn't exist!
// -- Server Down --
// java.net.SocketException: Connection reset by peer: JVM_recv in socket input stream read
// java.net.SocketException: Unexpected end of file from server.
// -- Post page not found --
// java.io.FileNotFoundException: <<URL>>
bInp = new BufferedReader(new InputStreamReader(urlConn.getInputStream ()));

String str;
while (null != ((str = bInp.readLine()))){
}catch(Exception e){
this.e = e;
}catch(Exception e){}
bInp = null;
}catch(Exception e){}
dOut = null;
urlConn = null;
url = null;

private String getRandomString(){
String alphaNum="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuffer sbRan = new StringBuffer(11);
int num;
for(int i = 0; i < 11; i++){
num = (int)(Math.random()* (alphaNum.length() - 1));
sbRan.append(alphaNum.substring(num, num+1));
return sbRan.toString();

private void uploadFileStream(File f, DataOutputStream dOut)
throws FileNotFoundException,
byte[] byteBuff = null;
FileInputStream fis = null;
int numBytes = 0;
byteBuff = new byte[1024];
fis = new FileInputStream(f);
while(-1 != (numBytes = fis.read(byteBuff)) && !stop){
dOut.write(byteBuff, 0, numBytes);
uploadedLength += numBytes;
if(null != progress) progress.setValue((int)uploadedLength);
}catch(Exception e){}
byteBuff = null;
GeeCON Prague 2014
subject: connect to a UploadServlet