Multipart form upload

Hi there,

I am trying to do a http post to upload a file to my web server using multipart/form-data to a URLConnection for posting. I am using the "MultiPartFormOutputStream".

I am able to reach the url, but it failed to post the request.I've been stuck on this for a while, any help is appreciated! I need to set the name of the content to "Report", see below:

Content-Disposition: form-data; name="Report";

filename="/etc/2007_report.txt"

My code below:

URL url =null;

try{

url =new URL("http://localhost/rsa/upload/report.htm");

}catch (MalformedURLException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

// Create a boundary string

String boundary = MultiPartFormOutputStream.createBoundary();

// Creating a URL connection

try{

urlConn = MultiPartFormOutputStream.createConnection(url);

}catch (IOException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

urlConn.setRequestProperty("Accept","*/*");

urlConn.setRequestProperty("Content-Type", MultiPartFormOutputStream

.getContentType(boundary));

// Setting Request Properties

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

urlConn.setRequestProperty("Cache-Control","no-cache");

//

urlConn.setRequestProperty("Content-Disposition",

"form-data; name='Report'; filename='/etc/2007_report.txt'");

urlConn.setRequestProperty("Content-Type",

"application/x-test-report");

// Finally ready to create our MultipartFormoutputStream object

MultiPartFormOutputStream out =null;

try{

out =new MultiPartFormOutputStream(urlConn.getOutputStream(),

boundary);

}catch (IOException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

// Adding finalFile to Output Stream

try{

out.writeFile("myFile","text/plain",new File("/etc/2007_report.txt"));

out.close();

out.flush();

}catch (IOException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

// read response from server

try{

BufferedReader in =new BufferedReader(new InputStreamReader(

urlConn.getInputStream()));

String line ="";

while ((line = in.readLine()) !=null){

System.out.println(line);

}

in.close();

System.out.println("File written and closed");

}catch (IOException e){

// TODO Auto-generated catch block

e.printStackTrace();

}

}

[4643 byte] By [cup_joea] at [2007-11-27 8:54:12]
# 1
urlConn.setRequestProperty("Content-Type","application/x-test-report");There is a mime type specifically for "multipart/form-data". Your server probably has no clue what an "application/'x-test-report" file is.
kevjavaa at 2007-7-12 21:13:13 > top of Java-index,Java Essentials,Java Programming...
# 2

Thanks for the respond. We are using Content-Type: multipart/form-data; boundary=7d731c34ab00fe

I've modified the code to include the mime type but it is still failing to post:

private File messageFile = new File("/etc/2007_report.txt");

BufferedReader br1 = null;

try {

br1 = new BufferedReader(new FileReader(messageFile));

} catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

String line = "";

String message = "";

try {

while ((line = br1.readLine()) != null) {

message = message + "\n" + line;

}

} catch (IOException e) {

System.out.println("Error message is: " + e.getMessage());

e.printStackTrace();

}

return message;

}

/*

* it to a URL specified in the URL

*/

public void sendRequest() {

// Creating URl

URL url = null;

try {

url = new URL("http://localhost/rsa/report.htm");

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// Create a boundary string

String boundary = MultiPartFormOutputStream.createBoundary();

// Creating a URL connection

try {

urlConn = MultiPartFormOutputStream.createConnection(url);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

urlConn.setRequestProperty("Accept", "*/*");

urlConn.setRequestProperty("Content-Type", MultiPartFormOutputStream

.getContentType(boundary));

// Setting Request Properties

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

urlConn.setRequestProperty("Cache-Control", "no-cache");

// Finally ready to create our MultipartFormoutputStream object

MultiPartFormOutputStream out = null;

try {

out = new MultiPartFormOutputStream(urlConn.getOutputStream(),

boundary);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// Adding finalFile to Output Stream

try {

out.writeFile("Report", "multipart/form-data", messageFile);

out.close();

out.flush();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// read response from server

try {

BufferedReader in = new BufferedReader(new InputStreamReader(

urlConn.getInputStream()));

String line = "";

while ((line = in.readLine()) != null) {

System.out.println(line);

}

in.close();

System.out.println("File written and closed");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

cup_joea at 2007-7-12 21:13:13 > top of Java-index,Java Essentials,Java Programming...
# 3

One thing might help if you said where you found this MultiPartFormOutputStream class. Presumably you mean from here:

http://forum.java.sun.com/thread.jspa?forumID=31&threadID=451245

In which case, it's been a while, but it looks like you are doing the correct things, except possibly:

a) Are you sure your messageFile file exists?

b) I don't think your file's mime-type should be "multipart/form-data", but "text/plain".

c) What is that BufferedReader stuff doing? Maybe you are calling that and not closing the reader before trying to read the file again?

d) calling out.flush() is unnecessary (although generally, you call flush before close, but just calling MultiPartFormOutputStream.close() is enough, as it has to write other stuff out anyway.)

Otherwise, what errors do you see on either side?

bsampieria at 2007-7-12 21:13:13 > top of Java-index,Java Essentials,Java Programming...
# 4

Hi ,

Yes, I took the code from http://forum.java.sun.com/thread.jspa?forumID=31&threadID=451245

1. Yes, the file exist.

2. I'm not sure multipart/form-data is what I want, but I'm loading it to a servlet with an HTML form interface. I'd chaned it to "text/plain," as the mime type, but still code failed :(

3.The BufferedReader was just a way to get the length. I don't need it so I removed it, and I also removed the flush()

I've been trying to used the code for couple of days, and I never were able to do the post, I got no error when running the code it just spits out the form source page I am connecting to (please note* it never post to name="Report") because if it did I would have gotten back a success or failure message from the web server.

This is what i get back when running the code:

Entering HTTPUploadReport message

<HTML>

<HEAD

><TITLE>Report Uploader</TITLE>

</HEAD>

<BODY>

<FORM method="POST" action="/rsa/upload/" enctype="multipart/form-data">

<input type="file" id="Report" name="Report">

<input type="submit" value="submit">

</FORM>

Any help is appreciated!

cup_joea at 2007-7-12 21:13:13 > top of Java-index,Java Essentials,Java Programming...
# 5

Below is my entire class for your reference. Basically I need to send the file to my webapp setting the name of the content to "Report", see below:

Content-Disposition: form-data; name="Report";

filename="C:\\2007_report.txt");

class HTTPUploadReport {

private File messageFile = new File("C:\\2007_report.txt");

public static void main(String[] args) {

System.out.println("Entering HTTPUploadReport");

HTTPUploadReport humr = new HTTPUploadReport();

humr.sendRequest();

}

public void sendRequest() {

// Creating URl

URL url = null;

try {

url = new URL("http://localhost/rsa/upload/report.htm");

} catch (MalformedURLException e) {

e.printStackTrace();

}

// Create a boundary string

String boundary = MultiPartFormOutputStream.createBoundary();

// Creating a URL connection

try {

urlConn = MultiPartFormOutputStream.createConnection(url);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

urlConn.setRequestProperty("Accept", "*/*");

urlConn.setRequestProperty("Content-Type", MultiPartFormOutputStream

.getContentType(boundary));

// Setting Request Properties

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

urlConn.setRequestProperty("Cache-Control", "no-cache");

// Finally ready to create our MultipartFormoutputStream object

MultiPartFormOutputStream out = null;

try {

out = new MultiPartFormOutputStream(urlConn.getOutputStream(),

boundary);

} catch (IOException e) {

e.printStackTrace();

}

// Adding finalFile to Output Stream

try {

out.writeFile("Report", "text/plain", messageFile);

out.close();

} catch (IOException e) {

e.printStackTrace();

}

// read response from server

try {

BufferedReader in = new BufferedReader(new InputStreamReader(

urlConn.getInputStream()));

String line = "";

while ((line = in.readLine()) != null) {

System.out.println(line);

}

in.close();

System.out.println("File written and closed");

} catch (IOException e) {

e.printStackTrace();

}

}

}

cup_joea at 2007-7-12 21:13:13 > top of Java-index,Java Essentials,Java Programming...
# 6

Don't take this personally, but...

"http://localhost/rsa/upload/report.htm"

What is that? If that's a plain HTML page then your problem is a total lack of understanding how HTTP works.

You need a servlet or CGI or PHP script or something on the server that can process the request and do something with the file. Simply "posting" a file to a web server is not going work. That's not how POST requests work.

(PUT, maybe, but of course, web servers don't typically support PUT because of security reasons.)

bsampieria at 2007-7-12 21:13:13 > top of Java-index,Java Essentials,Java Programming...