1

I finally made it to upload a file using core java. Here is my code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class FileUpload {

    public static final String C_EMAIL = "email@gmail.com";
    public static final String C_PASSWORD = "password";

    public static void main(String args[]) {
        try {
            // Send data
            String url = "http://localhost/upload.php";
            File binaryFile = new File("C:\\wamp\\www\\image.png");
            // Just generate some unique random value.
            String boundary = Long.toHexString(System.currentTimeMillis());
            // Line separator required by multipart/form-data.
            String CRLF = "\r\n";
            URLConnection connection = new URL(url).openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
            PrintWriter writer = null;
            try {
                OutputStream output = connection.getOutputStream();
                // true = autoFlush, important!
                writer = new PrintWriter(
                        new OutputStreamWriter(output, "UTF-8"), true);
                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"email\"")
                        .append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "UTF-8")
                        .append(CRLF);
                writer.append(CRLF);
                writer.append(C_EMAIL).append(CRLF).flush();
                // Send binary file.
                writer.append("--" + boundary).append(CRLF);
                writer.append(
                    "Content-Disposition: form-data;"
                        + "name=\"file\"; filename=\"" + binaryFile.getName()
                        + "\"").append(CRLF);
                writer.append("Content-Type: "
                    + URLConnection.guessContentTypeFromName(binaryFile
                            .getName()) + CRLF);
                writer.append("Content-Transfer-Encoding: binary").append(CRLF);
                System.out.println("Content transfer set");
                writer.append(CRLF).flush();
                InputStream input = null;
                try {
                    System.out.println("Entered try");
                    input = new FileInputStream(binaryFile);
                    byte[] buffer = new byte[1024];
                    System.out.println("Before for loop");
                    for (int length = 0; (length = input.read(buffer)) > 0;) {
                        output.write(buffer, 0, length);
                    }
                    output.flush(); // Important! Output cannot be closed.
                    // Close of writer will close output as well.
                    System.out.println("output flushed");
                } finally {
                    if (input != null) try {
                        input.close();
                    } catch (IOException logOrIgnore) {}
                }
                writer.append(CRLF).flush(); // CRLF is important! It indicates
                // end of binary boundary.
                // End of multipart/form-data.
                writer.append("--" + boundary + "--").append(CRLF);
            } finally {
                if (writer != null) writer.close();
            }
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            rd.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

In my PHP script I am able to get the file being uploaded and the 'email' parameter with its value.
However, I don't know how can I pass one more additional parameter i.e. "password".
Can anybody suggest me?

Mr_and_Mrs_D
  • 27,070
  • 30
  • 156
  • 325
Mahendra Liya
  • 11,166
  • 10
  • 79
  • 105
  • A lot of questions [have been asked on this topic](http://stackoverflow.com/search?q=java+file+upload+multipart+post). And, asking for code handouts is not encouraged; post the code you've been working on, and the related problem if any. – Vineet Reynolds Jun 11 '11 at 13:23

1 Answers1

0

Use either the API provided java.net.URLConnection or the more convenient Apache HttpComponents Client.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452