3

I'm trying to make a program that uploads a image to a webserver that accepts multipart file-uploads.

More specificly i want to make a http POST request to http://iqs.me that sends a file in the variable "pic".

I've made a lot of tries but i don't know if i've even been close. The hardest part seems to be to get a HttpURLConnection to make a request of the type POST. The response i get looks like it makes a GET.

(And i want to do this without any third party libs)

UPDATE: non-working code goes here (no errors but doesn't seem to do a POST):

  HttpURLConnection conn = null;
  BufferedReader br = null;
  DataOutputStream dos = null;
  DataInputStream inStream = null;

  InputStream is = null;
  OutputStream os = null;
  boolean ret = false;
  String StrMessage = "";
  String exsistingFileName = "myScreenShot.png";

  String lineEnd = "\r\n";
  String twoHyphens = "--";
  String boundary =  "*****";

  int bytesRead, bytesAvailable, bufferSize;
  byte[] buffer;
  int maxBufferSize = 1*1024*1024;
  String responseFromServer = "";
  String urlString = "http://iqs.local.com/index.php";


  try{
    FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) );
    URL url = new URL(urlString);
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setUseCaches(false);

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

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

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd);
    dos.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    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);
    }

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

    fileInputStream.close();
    dos.flush();
    dos.close();


  }catch (MalformedURLException ex){
    System.out.println("Error:"+ex);
  }catch (IOException ioe){
    System.out.println("Error:"+ioe);
  }

  try{
    inStream = new DataInputStream ( conn.getInputStream() );
    String str;
    while (( str = inStream.readLine()) != null){
      System.out.println(str);
    }
    inStream.close();
  }catch (IOException ioex){
    System.out.println("Error: "+ioex);
  }
Martin
  • 5,197
  • 11
  • 45
  • 60
  • Please post your code, otherwise we can hardly help you... – Péter Török Apr 15 '10 at 14:40
  • I don't have the time to go through all of this right now, but I've posted answers with working code samples before, you may find it useful as well: [here](http://stackoverflow.com/questions/2469451/upload-files-with-java/2469587#2469587) and a follow-up [here](http://stackoverflow.com/questions/2477449/simple-stream-read-write-question-in-java/2478127#2478127). To keep all the verbosity down and ease all the work, I strongly recommend to go ahead with [Apache HttpComponents HttpClient](http://hc.apache.org/httpcomponents-client/index.html). – BalusC Apr 15 '10 at 14:58
  • That solved it, very good examples. Thanks! – Martin Apr 15 '10 at 15:17
  • Do you want me to post it as an answer so that you can accept it? – BalusC Apr 15 '10 at 15:55

2 Answers2

2

Two things:

  1. Make sure you call setRequestMethod to set the HTTP request to be a POST. You should be warned that doing multipart POST requests by hand is difficult and error-prone.

  2. If you're running on *NIX, the tool netcat is very useful for debugging this stuff. Run
    netcat -l -p 3000

    and point your program to port 3000; you'll see exactly what the program is sending (Control-C to close it afterwards).

Amanda S
  • 3,266
  • 4
  • 33
  • 45
James Kingsbery
  • 7,298
  • 2
  • 38
  • 67
  • I'm setting it to "POST". Not running *NIX right now but good tip, will use that another time. – Martin Apr 15 '10 at 14:53
0

I have used this and found it useful in multipart file upload

File f = new File(filePath);
PostMethod filePost = new PostMethod(url);
Part[] parts = { new FilePart("file", f) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,
filePost.getParams()));
HttpClient client = new HttpClient();
status = client.executeMethod(filePost);
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Aashish Katta
  • 1,174
  • 3
  • 13
  • 22