1

I am using the following Android / PHP code to upload a file to a server. All works well unless the original file name has a space in it, at which point it fails.

Android: (the space in question is in the String path variable)

public static void uploadFile(String path,String group,String folder) {



        HttpURLConnection conn = null;


            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            try {
                // ------------------ CLIENT REQUEST



                FileInputStream fileInputStream = new FileInputStream(new File(
                        path));





                // open a URL connection to the Servlet

                URL url = new URL("http://uploadsite.php" +
                        "?group_name=" + group + "&folder=" + folder  );

                // Open a HTTP connection to the URL

                conn = (HttpURLConnection) url.openConnection();

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod("POST");

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

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



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

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                                + path + "" + lineEnd);
                dos.writeBytes(lineEnd);
                // create a buffer of maximum size



                int bytesAvailable = fileInputStream.available();
                int maxBufferSize = 1*1024*1024;

                byte[] buffer = new byte[bytesAvailable];

                // read file and write it into form...

                int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

                while (bytesRead > 0) {
                    dos.write(buffer, 0, bytesAvailable);
                    bytesAvailable = fileInputStream.available();
                    bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
                }

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

                // close streams

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

            } catch (MalformedURLException ex) {
                Log.e(TAG, "error: " + ex.getMessage(), ex);
            }

            catch (IOException ioe) {
                Log.e(TAG, "error: " + ioe.getMessage(), ioe);
            }

            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    Log.e(TAG, "Message: " + line);
                }
                rd.close();

            } catch (IOException ioex) {
                Log.e(TAG, "error: " + ioex.getMessage(), ioex);
            }
            return;
}

PHP:

<?php

 $group = $_GET["group_name"];
 $folder = $_GET["folder"];
 $base_path  = "./db/";

 $path = $base_path . $group;



$target_path = $path . "/" . $folder . "/" . basename( $_FILES['uploadedfile']['name']);

$group = ( $_FILES['group_name']['name']);



$file = basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
    chmod ($path.basename( $_FILES['uploadedfile']['name']), 0777);
} else{
    echo "There was an error uploading the file, please try again!(".basename( $_FILES['uploadedfile']['name']).")";
}
?>

Any suggestions on how I can upload this file without changing the file name on the android side?

Thanks Josh

Josh
  • 2,685
  • 6
  • 33
  • 47

2 Answers2

5

some characters got special meaning when used in URLs. That's why you always have to properly encode your string to be part of url. With Java you can use URLEncoder class to do the job. So your

dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                            + path + "" + lineEnd);

should look

dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                            + URLEncoder.encode(path, "UTF-8") + lineEnd);

EDIT

If you need to decode string back to its original form, then on PHP side you can use urldecode()

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • This is encoding the entire path to the data folder the file is held in and still failing: /data/data/com.name.app/databases/DBGjggu Utshu.DB becomes %2Fdata%2Fdata%2Fcom.name.app%2Fdatabases%2FDBGjggu+Utshu.DB – Josh Jul 07 '13 at 16:41
  • You wrote **the space in question is in the String path variable**. But now you know what you done wrong. so even if my answer does not address all occurences of strings requiring escape, you should have no problem fixing that yourself (assuming you understand your own code :) – Marcin Orlowski Jul 07 '13 at 16:43
  • The file now uploads, but the problem I have is that the filename of the upload now includes the entire path ( %2Fdata....shu.DB ). – Josh Jul 07 '13 at 16:49
  • Your answer seems correct. I just need to understand how to decode the String path from $_FILES in order to get the basepath for the server side file. – Josh Jul 07 '13 at 18:07
0

you should encode url which contains white spaces or special symbols etc ..

to encode use

     URLEncoder.encode("your url here");

for your code use:

    URL url = new URL("http://uploadsite.php" +
                    "?group_name=" + URLEncoder.encode(group) + "&folder=" + URLEncoder.encode(folder)  );

for more info visit this Question may help you : URL encoding in Android

Community
  • 1
  • 1
Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71