This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "connect to a UploadServlet" Watch "connect to a UploadServlet" New topic
Author

connect to a UploadServlet

Holger Prause
Ranch Hand

Joined: Oct 09, 2000
Posts: 47
Hi
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.
con.setRequestProperty("Content-type","multipart/form-data");
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,
Holger

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?

con.setRequestProperty("key,value"+boundary);
thx,
Holger
Holger Prause
Ranch Hand

Joined: Oct 09, 2000
Posts: 47
Heres the Solution
<pre>
public void sendFileToServer(File file) throws IOException {
//get the UserDirectory from the Session Servlet
StreamParser parser = new StreamParser(con.getInputStream());
parser.parse();
String result = parser.getUserDirectory();
connectToServer(new URL("ServletURL?Directory="+result));
String boundary="---------------------------7d021a37605f0";
HttpURLConnection conn = (HttpURLConnection)con ;
conn.setDoOutput( true );
conn.setDoInput ( true );
conn.setFollowRedirects(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 );
outStream.close();
//get the Response from the Servlet
StreamWriter writer = new StreamWriter(con.getInputStream());
writer.writeToDisk(new File("/home/hp/logs/uploaded.txt"));
}
</pre>
Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Hi,
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
Aniken
Greenhorn

Joined: Jun 21, 2005
Posts: 3
public void run() {
URL url = null;
URLConnection urlConn = null;
DataOutputStream dOut = null;
BufferedReader bInp = null;
try{
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();
urlConn.setRequestProperty("Content-Type",
"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;
progress.setMaximum((int)totalFilesLength);
for(int i=0; i < aTotalFiles.length && !stop; i++){
f = aTotalFiles[i];
sb = new StringBuffer();
// Line 1.
sb.append(boundary);sb.append(CRLF);
// Line 2.
sb.append("Content-Disposition: form-data; name=\"File");sb.append(i);
sb.append("\"; filename=\"");sb.append(f.toString());
sb.append("\"");sb.append(CRLF);
// Line 3 & Empty Line 4.
sb.append("Content-Type: application/octet-stream");
sb.append(CRLF);sb.append(CRLF);
// Write to Server the 4 Lines, a File and the CRLF.
dOut.writeBytes(sb.toString());
uploadFileStream(f,dOut);
dOut.writeBytes(CRLF);
}
// Telling the Server we have Finished.
dOut.writeBytes(boundary);dOut.writeBytes("--");dOut.writeBytes(CRLF);
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()))){
this.addServerOutPut(str);
}
}catch(Exception e){
this.e = e;
}finally{
try{
bInp.close();
}catch(Exception e){}
bInp = null;
try{
dOut.close();
}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,
IOException{
byte[] byteBuff = null;
FileInputStream fis = null;
try{
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);
}
}finally{
try{
fis.close();
}catch(Exception e){}
byteBuff = null;
}
}
}
 
Don't get me started about those stupid light bulbs.
 
subject: connect to a UploadServlet
 
Similar Threads
Unable to upload file using Commons HTTPClient and Commons FileUpload
uploading an image functionality
Setting Content - Boundary in a XMLHttpRequest object
Struts FileUpload - Multipart data doesn't start with boundary
BufferedWriter for Mulitple file type