How to  send HTTP File from Java App

mscproj
mscproj used Ask the Experts™
on
I have a servlet which can accept the follow HTTP Form File operation, and save the file into the server's File System

<FORM METHOD="POST" ACTION="http://localhost:8080/servlet/servletUpload" ENCTYPE="multipart/form-data">
   Select the file to upload  : <INPUT TYPE="FILE" NAME="FILE1" SIZE="25"><BR>
   <INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM>

How can I write a Java Client that does the same thing?

E.g.
java JavaUpload file_location
e.g. java JavaUpload "c:\data upload\abc.txt"

Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Java Developer
Top Expert 2010
Commented:
The following library does what you require:
http://www.servlets.com/cos/index.html
try this :

try
{
String CONTENT_BOUNDARY = "-----------------------------7d22a63810058e";
URL url = new URL("http://www.testing.com/servlet/testing");

URLConnection uc = url.openConnection();
uc.setAllowUserInteraction(true);
uc.setDoOutput(true);
uc.setDoInput(true);

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

File f = new File ( "C:/testing.txt" );

if ( myFileName == null )
{
     myFileName = f.getName();
}

OutputStream os = uc.getOutputStream();

// Field 1 a Field of data
os.write((CONTENT_BOUNDARY + "\r\n" +
"Content-Disposition: form-data; name=\"callrepOID\"\r\n\r\n" + callReportOID + "\r\n").getBytes());

os.write((CONTENT_BOUNDARY + "\r\n" +
"Content-Disposition: form-data; name=\"FILE1\"; filename=\"" +
myFileName + "\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes());

FileInputStream fis = new FileInputStream( f );
int data = -1;
while ( (data = fis.read() ) != -1 )
{
     os.write( data );
}

os.write(("\r\n" + CONTENT_BOUNDARY + "--\r\n").getBytes());
os.flush();
os.close();
fis.close();    
}
catch( Exception e )
{}
mscproj:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.

Commented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- Split points between objects and kokchoon78

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Venabili
EE Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial