how to upload a file over internet

Hi Friends,

I am having trouble uploading file on the server. I have a file on my local computer say C:/media.wav and I would like to make a java program,so that if I pass the URL of some server,it should automatically copy that file to that location. We assume here all the permissions are set properly. For example,if somebody does this:

java ServletCom http://www.xyz.com/test/

The program should copy the "C:/media.wav" file under the "test"directory of the webserver. IS this possible to do?

I tried using the following code,and its reading the response back from the server but its not able to copy the file,can someone please help me...

import java.io.*;

import java.net.*;

publicclass ServletCom{

publicstaticvoid main(String[] args)

throws Exception

{

HttpURLConnection conn =null;

BufferedReader br =null;

DataOutputStream dos =null;

DataInputStream inStream =null;

InputStream is =null;

OutputStream os =null;

boolean ret =false;

String StrMessage ="";

//The file to copy

String exsistingFileName ="C:\\media.wav";

String lineEnd ="\r\n";

String twoHyphens ="--";

String boundary ="*****";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1*1024*1024;

String responseFromServer ="";

//The url to post the file to

String urlString = args[0];

try

{

// CLIENT REQUEST

FileInputStream fileInputStream =new FileInputStream(new

File(exsistingFileName) );

// open a URL connection to the Servlet

URL url =new URL(urlString);

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();

// Allow Inputs

conn.setDoInput(true);

// Allow Outputs

conn.setDoOutput(true);

// Don't use a cached copy.

conn.setUseCaches(false);

// Use a post method.

conn.setRequestMethod("POST");

conn.setRequestProperty("Connection","Keep-Alive");

// conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

conn.setRequestProperty("Content-Type","audio/wav");

dos =new DataOutputStream( conn.getOutputStream() );

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"upload\";"

+" filename=\"" + exsistingFileName +"\"" + lineEnd);

dos.writeBytes(lineEnd);

// create a buffer of maximum size

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

buffer =newbyte[bufferSize];

// read file and write it into form...

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)

{

dos.write(buffer, 0, bufferSize);

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);

dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams

fileInputStream.close();

dos.flush();

dos.close();

}

catch (MalformedURLException ex)

{

System.out.println("From ServletCom CLIENT REQUEST:"+ex);

}

catch (IOException ioe)

{

System.out.println("From ServletCom CLIENT REQUEST:"+ioe);

}

// read the SERVER RESPONSE

try

{

inStream =new DataInputStream ( conn.getInputStream() );

String str;

while (( str = inStream.readLine()) !=null)

{

System.out.println("Server response is: "+str);

System.out.println("");

}

inStream.close();

}

catch (IOException ioex)

{

System.out.println("From (ServerResponse): "+ioex);

}

}

}

[6781 byte] By [java80a] at [2007-11-27 10:38:47]
# 1

Don't use available() method. It is almost useless and unreliable. For POST request, you should send Content-Length req-header. See the code below:

int len;

String contLen;

byte[] buf;

ByteArrayOutputStream baos;

FileInputStream fis;

// create and configure the connection

// ...

// ...

// ...

try{

baos = new ByteArrayOutputStream();

fis = new FileInputStream("C:/media.wav");

buf = new byte[4096];

while ((len = fis.read(buf)) >= 0){

baos.write(buf, 0, len);

}

contLen = String.valueOf(baos.size());

// declare POST data

connection.setRequestProperty("Content-Length", contLen);

connection.setRequestProperty("Content-Type", "audio/wav");

baos.writeTo(connection.getOutputStream());

// read and process the response

// ...

// ...

// ...

}

hiwaa at 2007-7-28 18:56:53 > top of Java-index,Java Essentials,Java Programming...
# 2

Thanks a lot Hiwa,

I tried your suggestion but still the same,the file does not get stored on the server. I get a proper reponse back and everything looks fine but when I see the directory there is no file uploaded. I tried it with both apache and tomcat.The apache logs even show a POST request coming,but why is it not storing the file,pleaseeeee help.....

here's the modified code i am using now:

import java.io.*;

import java.net.*;

public class ServletCom {

public static void main(String[] args) throws Exception

{

int len=0;

String contLen=null;

byte[] buf=null;

ByteArrayOutputStream baos=null;

FileInputStream fis=null;

HttpURLConnection connection = null;

BufferedReader br = null;

DataOutputStream dos = null;

DataInputStream inStream = null;

InputStream is = null;

OutputStream os = null;

boolean ret = false;

String StrMessage = "";

//The file to copy

String exsistingFileName = "C:\\media.wav";

String lineEnd = "\r\n";

String twoHyphens = "--";

String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1*1024*1024;

String responseFromServer = "";

//The url to post the file to

String urlString = args[0];

URL url = new URL(urlString);

// Open a HTTP connection to the URL

connection = (HttpURLConnection) url.openConnection();

connection.setDoInput(true);

connection.setDoOutput(true);

connection.setUseCaches(false);

connection.setRequestMethod("POST");

connection.setRequestProperty("Connection", "Keep-Alive");

baos = new ByteArrayOutputStream();

fis = new FileInputStream("C:/tester.wav");

buf = new byte[4096];

while ((len = fis.read(buf)) >= 0){

baos.write(buf, 0, len);

}

contLen = String.valueOf(baos.size());

// declare POST data

connection.setRequestProperty("Content-Length", contLen);

connection.setRequestProperty("Content-Type", "audio/wav");

baos.writeTo(connection.getOutputStream());

// read the SERVER RESPONSE

try

{

inStream = new DataInputStream ( connection.getInputStream() );

String str;

while (( str = inStream.readLine()) != null)

{

System.out.println("Server response is: "+str);

System.out.println("");

}

inStream.close();

}

catch (IOException ioex)

{

System.out.println("From (ServerResponse): "+ioex);

}

}

}

java80a at 2007-7-28 18:56:53 > top of Java-index,Java Essentials,Java Programming...
# 3

> the file does not get stored on the server

There must be bugs on server-side code of your application.

hiwaa at 2007-7-28 18:56:53 > top of Java-index,Java Essentials,Java Programming...
# 4

Thats the thing..there is no server side code...this is the only class i am using..thats it.

I want that this class should store a file on the server...thats all...can you please tell me how to do this..as i am scratching my head since last 6-7 hours and still not able to find any solution....

I just want to copy a local file to the server location given using pure java...thts all..

Thanks

java80a at 2007-7-28 18:56:53 > top of Java-index,Java Essentials,Java Programming...
# 5

> there is no server side code

Then, your every effort should fail.

You must write a proper server-side code, may be a servlet, that should be specified in your URL string.

Your command line should be:

java ServletCom http://www.xyz.com/MyFilesaveServlet

hiwaa at 2007-7-28 18:56:53 > top of Java-index,Java Essentials,Java Programming...
# 6

> I get a proper reponse back

That should be a default/generic error response from the server.

hiwaa at 2007-7-28 18:56:53 > top of Java-index,Java Essentials,Java Programming...