Jump to content
Android Forum - A Community For Android Users and Enthusiasts

Android App upload file to PHP script


piggybank1974
 Share

Recommended Posts

Hi All,

This is driving me nuts so I'm asking for help.

I'm try to get my android test app to upload a file to my Synology box cs407.

I've tried it though a HTML form and it works ok

HTML code is: 

<html>
 <body>
  <form action="UploadToServer.php" method="post" enctype="multipart/form-data">
   <label for="file">Filename:</label>
   <input type="file" name="filename" id="filename"><br>
   <input type="submit" name="submit" value="Submit">
  </form>
 </body>
</html>

PHP Code is
 

<?php
 $allowedExts = array("gif", "jpeg", "jpg", "png");
 $temp = explode(".", $_FILES["filename"]["name"]);
$extension = end($temp);
 if ((($_FILES["filename"]["type"] == "image/gif")
 || ($_FILES["filename"]["type"] == "image/jpeg")
 || ($_FILES["filename"]["type"] == "image/jpg")
|| ($_FILES["filename"]["type"] == "image/pjpeg")
|| ($_FILES["filename"]["type"] == "image/x-png")
 || ($_FILES["filename"]["type"] == "image/png"))
 && ($_FILES["filename"]["size"] < 20000)
 && in_array($extension, $allowedExts))
   {
   if ($_FILES["filename"]["error"] > 0)
     {
     echo "Return Code: " . $_FILES["filename"]["error"] . "<br>";
     }
   else
     {
     echo "Upload: " . $_FILES["filename"]["name"] . "<br>";
     echo "Type: " . $_FILES["filename"]["type"] . "<br>";
     echo "Size: " . ($_FILES["filename"]["size"] / 1024) . " kB<br>";
     echo "Temp file: " . $_FILES["filename"]["tmp_name"] . "<br>";

     if (file_exists('uploads/' . $_FILES["filename"]["name"]))
       {
       echo $_FILES["filename"]["name"] . " already exists. ";
       }
     else
       {
       move_uploaded_file($_FILES["filename"]["tmp_name"], 'uploads/' . $_FILES["filename"]["name"]);
       echo "Stored in: " . 'uploads/' . $_FILES["filename"]["name"];
       }
     }
   }
 else
   {
   echo "Invalid file";
   }
 ?> 

The android code is:
 

public int uploadFile(String sourceFileUri, String MyFilename)
 {
  String fileName = sourceFileUri;
  HttpURLConnection conn = null;
  DataOutputStream dos = null;
  String lineEnd = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  int bytesRead, bytesAvailable, bufferSize;
  byte[] buffer;
  int maxBufferSize = 1 * 1024 * 1024;
  File sourceFile = new File(sourceFileUri);
  if (!sourceFile.isFile())
    {
//     dialog.dismiss();
  Log.e("uploadFile", "Source File not exist :" + imagepath);
   runOnUiThread(new Runnable()
   {
    public void run()
    {
     messageText.setText("Source File not exist :" + imagepath);
    }
   });
   return 0;
    }
    else
          {
           try
                {
                 // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);
                 // Open a HTTP  connection to  the URL
                  conn = (HttpURLConnection) url.openConnection();
                  conn.setDoInput(true);
                 // Allow Inputs
                  conn.setDoOutput(true);
                 // Allow Outputs
                  conn.setUseCaches(false); // Don't use a Cached Copy
                  conn.setRequestMethod("POST");
                  conn.setRequestProperty("Connection", "Keep-Alive");
                  //conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                  conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                  //conn.setRequestProperty("filename", fileName);
                  dos = new DataOutputStream(conn.getOutputStream());
                  dos.writeBytes(twoHyphens + boundary + lineEnd);
                  dos.writeBytes("Content-Disposition: form-data; name=\"filename\";filename=\""  + fileName + "\"" + lineEnd);
                  dos.writeBytes(lineEnd);
                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 buffer = new byte[bufferSize];
                 // read file and write it into form...
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                 int TotalBytes=bytesRead;

                  while (bytesRead > 0)
                  {
                   dos.write(buffer, 0, bufferSize);
                   bytesAvailable = fileInputStream.available();
                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                   TotalBytes += bytesRead;
                   Log.i("uploadFile", "Total is: " + TotalBytes);
                  }
                  // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                  // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();
                   Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
                   if (serverResponseCode == 200)
                     {
                      runOnUiThread(new Runnable()
                      {
                       public void run()
                       {
                       String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" +" F:/wamp/wamp/www/uploads";
                       messageText.setText(msg);
                       Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                       }
                      });
                     }
                 // close the streams //
                  fileInputStream.close();
                  dos.flush();
                  dos.close();
                }
           catch (MalformedURLException ex)
           {
       //    dialog.dismiss();
          ex.printStackTrace();
           runOnUiThread(new Runnable()
           {
           public void run()
           {
           messageText.setText("MalformedURLException Exception : check script url.");
           Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
           }
           });
          Log.e("uploadFile", "error: " + ex.getMessage(), ex);
            }
           catch (Exception e)
           {
          // dialog.dismiss();
           e.printStackTrace();
          runOnUiThread(new Runnable()
          {
          public void run() {
          messageText.setText("Got Exception : see logcat ");
          Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
          }
          });
           Log.e("uploadFile", "Exception : "  + e.getMessage(), e);
           }
      // dialog.dismiss();
      // return serverResponseCode;
       } // End else block

      return 0;
     }

so I call it like this:

[HIGH]
uploadFile("/storage/sdcard0/Pictures/Screenshots/Screenshot_2013-11-04-16-14-35.png");
[/HIGH]

I do get a response of 200 but there is no file on the server, the folder permissions are 777, which will go to 666 once I know it will work ok.

I'm using a Samsung Galaxy note 10.1 on my network.
thanks in advance

Link to comment
Share on other sites

  • 3 months later...
  • 3 months later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...