• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

connect to a UploadServlet

 
Holger Prause
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

>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
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 130
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Aniken
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic