views:

2749

answers:

4

Hello

I need a way to upload a file and POST it into php page...

My php page is:

<?php 
$maxsize = 10485760;
$array_estensioni_ammesse=array('.tmp');
$uploaddir = 'uploads/';
if (is_uploaded_file($_FILES['file']['tmp_name']))
{
    if($_FILES['file']['size'] <= $maxsize)
    {
     $estensione = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], "."), strlen($_FILES['file']['name'])-strrpos($_FILES['file']['name'], ".")));
     if(!in_array($estensione, $array_estensioni_ammesse))
     {
      echo "File is not valid!\n";
     }
     else
     {
      $uploadfile = $uploaddir . basename($_FILES['file']['name']); 
         echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n"; 
      if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))
      {
       echo "File is valid, and was successfully moved.\n";
      } 
      else 
       print_r($_FILES); 
     }
    }
    else
     echo "File is not valid!\n";
}
else
{ 
    echo "Upload Failed!!!"; 
    print_r($_FILES);
} 
?>

and i use this java code in my desktop application:

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setRequestMethod("POST");
        OutputStream os = httpUrlConnection.getOutputStream();
        Thread.sleep(1000);
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream("tmpfile.tmp"));

        for (int i = 0; i < totalByte; i++) {
            os.write(fis.read());
            byteTrasferred = i + 1;
        }

        os.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                httpUrlConnection.getInputStream()));

        String s = null;
        while ((s = in.readLine()) != null) {
            System.out.println(s);
        }
        in.close();
        fis.close();

But I receive always the "Upload Failed!!!" message...

Can you help me?

Thanks a lot

A: 

You are not using the correct HTML file upload semantics. You are just posting a bunch of data to the url.

You have 2 option here:

  • You can keep the java code as-is, and change the php code to just read the raw POST as a file.
  • Change the java code to do a real file upload possibly using a common library.

I'd recommend changing the java code to do this in a standards compliant way.

Byron Whitlock
Thanks but I don't want to use external libraries...How I can change the php code to just read the raw POST as a file?
To do that, you would need to use the socket example below. Be warned, that is going to be a LOT of extra code and probably a great deal of time spent debugging. Seriously consider your aversion to external libraries. (I understand sometimes your hands are tied, just realize it will likely be a lot easier)
Chris Thompson
but an easier way to upload a file (or data) does not exist?
+2  A: 

You need to use a form-multipart encoded post for PHP to be able to read it the way you are attempting. This website outlines a good way to do it and has links to libraries that can help you out.

Chris Thompson
+1  A: 

All above answers are 100% correct. You can also use plain sockets, in which case your method would look like this:

        // Compose the request header
        StringBuffer buf = new StringBuffer();
        buf.append("POST ");
        buf.append(uploader.getUploadAction());
        buf.append(" HTTP/1.1\r\n");
        buf.append("Content-Type: multipart/form-data; boundary=");
        buf.append(boundary);
        buf.append("\r\n");
        buf.append("Host: ");
        buf.append(uploader.getUploadHost());
        buf.append(':');
        buf.append(uploader.getUploadPort());
        buf.append("\r\n");
        buf.append("Connection: close\r\n");
        buf.append("Cache-Control: no-cache\r\n");

        // Add cookies
        List cookies = uploader.getCookies();
        if (!cookies.isEmpty())
            {
                buf.append("Cookie: ");
                for (Iterator iterator = cookies.iterator(); iterator.hasNext(); )
                    {
                        Parameter parameter = (Parameter)iterator.next();

                        buf.append(parameter.getName());
                        buf.append('=');
                        buf.append(parameter.getValue());

                        if (iterator.hasNext())
                            buf.append("; ");
                    }

                buf.append("\r\n");
            }

        buf.append("Content-Length: ");

        // Request body
        StringBuffer body = new StringBuffer();
        List fields = uploader.getFields();
        for (Iterator iterator = fields.iterator(); iterator.hasNext();)
            {

                Parameter parameter = (Parameter) iterator.next();

                body.append("--");
                body.append(boundary);
                body.append("\r\n");
                body.append("Content-Disposition: form-data; name=\"");
                body.append(parameter.getName());
                body.append("\"\r\n\r\n");
                body.append(parameter.getValue());
                body.append("\r\n");
            }

        body.append("--");
        body.append(boundary);
        body.append("\r\n");
        body.append("Content-Disposition: form-data; name=\"");
        body.append(uploader.getImageFieldName());
        body.append("\"; filename=\"");
        body.append(file.getName());
        body.append("\"\r\n");
        body.append("Content-Type: image/pjpeg\r\n\r\n");

        String boundary = "WHATEVERYOURDEARHEARTDESIRES";
        String lastBoundary = "\r\n--" + boundary + "--\r\n";
        long length = file.length() + (long) lastBoundary.length() + (long) body.length();
        long total = buf.length() + body.length();

        buf.append(length);
        buf.append("\r\n\r\n");

        // Upload here
        InetAddress address = InetAddress.getByName(uploader.getUploadHost());
        Socket socket = new Socket(address, uploader.getUploadPort());
        try
            {
                socket.setSoTimeout(60 * 1000);
                uploadStarted(length);

                PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
                out.print(buf);
                out.print(body);

                // Send the file
                byte[] bytes = new byte[1024 * 65];
                int size;
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                try
                    {
                        while ((size = in.read(bytes)) > 0)
                            {
                                total += size;
                                out.write(bytes, 0, size);
                                transferred(total);
                            }
                    }
                finally
                    {
                        in.close();
                    }

                out.print(lastBoundary);
                out.flush();

                // Read the response
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (reader.readLine() != null);
            }
        finally
            {
                socket.close();
            }
Daniil
but an easier way to upload a file (or data) does not exist?
Thats as easy as it gets. Anything else is just using libraries.
Daniil
A: 

I realize this is a bit old but I just posted an answer to a similar question that should be applicable here as well. It includes code similar to Daniil's, but uses HttpURLConnection instead of a Socket.

Lauri Lehtinen