0

I'm trying to upload image on server but in specific folder using php.

This is PHP script:

<?php   

$subfolder = $_POST['subfolder'];
mkdir($subfolder, 0755, true);

if(@move_uploaded_file($_FILES["filUpload"]["tmp_name"],"upload/".$subfolder.$_FILES["filUpload"]["name"]))
{
    $arr["StatusID"] = "1";
    $arr["Error"] = "";
}
else
{
    $arr["StatusID"] = "0";
    $arr["Error"] = "Cannot upload file.";
}

echo json_encode($arr);
?>

And this is how I'm sending image:

//Upload
    public void startUpload() {     

        Runnable runnable = new Runnable() {

            public void run() {


                handler.post(new Runnable() {
                    public void run() {

                        new UploadFileAsync().execute();    
                    }
                });

            }
        };
        new Thread(runnable).start();
    }

     // Async Upload
    public class UploadFileAsync extends AsyncTask<String, Void, Void> {

        String resServer;


        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            int resCode = 0;
            String resMessage = "";

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


            String strSDPath = selImgPath;

            // Upload to PHP Script
            String strUrlServer = "http://localhost/zon/uploadFile.php";

            try {
                /** Check file on SD Card ***/
                File file = new File(strSDPath);
                if(!file.exists())
                {
                    resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
                    return null;
                }

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

                URL url = new URL(strUrlServer);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");

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


                DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("");


                outputStream.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\"" + file.getName().toString() + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);


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

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

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

                // Response Code and  Message
                resCode = conn.getResponseCode();
                if(resCode == HttpURLConnection.HTTP_OK)
                {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int read = 0;
                    while ((read = is.read()) != -1) {
                          bos.write(read);
                    }
                    byte[] result = bos.toByteArray();
                    bos.close();

                    resMessage = new String(result);                        

                }

                fileInputStream.close();
                outputStream.flush();
                outputStream.close();

                resServer = resMessage.toString();

                System.out.println("RES MESSAGE = " + resMessage.toString());

            } catch (Exception ex) {            
                return null;
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // statusWhenFinish(position,resServer);
        }

    }

The part that I don't understand is how to send parameter that is reserved for creating subfolder on server.

8
  • check stackoverflow.com/questions/2017414/… Commented Apr 30, 2015 at 11:45
  • You cannot pass an extra parameter in that line. You can however post as many key=value parameters extra as you want. Use them to tell the subfolder to the php script. Commented Apr 30, 2015 at 12:23
  • I'm not sure how to do that? This is the first time that i'm using this approach. Do you have example for this? Commented Apr 30, 2015 at 12:32
  • Whenever uploading images, remember to set your form ENCTYPE to `multipart/form-data´. Commented Apr 30, 2015 at 12:53
  • new UploadFileAsync().execute(); That should be the only statement in startUpload. Remove all othe code. You don't need that thread as the AsyncTask is already a thread. Commented May 4, 2015 at 13:52

2 Answers 2

1

After

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

Add following lines:

        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"subfolder\"" + lineEnd);
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(subfolder + lineEnd);

Where String subfolder contains the subfolder name.

At php side you can extract it in the normal way with $subfolder=$_POST['subfolder'];

EDIT:

Change your script to:

<?php   
error_reporting( E_ALL );
ini_set('display_errors', '1');

var_dump($_POST);
print_r($_FILES);

if ( ! isset($_POST['subfolder']) )
{
echo ("Sorry no 'subfolder' in POST array.\n");
exit();
}

$subfolder = $_POST['subfolder'];

$targetpath = "upload/" . $subfolder;

echo ( "subfolder: ". $subfolder . "\n");
echo ( "targetpath: ". $targetpath . "\n");

if ( ! file_exists( $targetpath ) )
 {
if ( ! mkdir( $targetpath, 0755, true) )
    echo ("error could not mkdir(): " . $targetpath . "\n");
else
    echo ("mkdir() created: " . $targetpath . "\n");
}

if(move_uploaded_file($_FILES["filUpload"]["tmp_name"], $targetpath . "/". $_FILES["filUpload"]["name"]))
{
$arr["StatusID"] = "1";
$arr["Error"] = "";
}
else
{
$arr["StatusID"] = "0";
$arr["Error"] = "Cannot upload file.";
}

echo json_encode($arr);
?>

Change if(resCode == HttpURLConnection.HTTP_OK) to //if(resCode == HttpURLConnection.HTTP_OK).

Sign up to request clarification or add additional context in comments.

7 Comments

If you want help you should supply more info. Your php script for example. And come more to the point: what happens instead?
See updated my first post. I've pasted code for sending image to server and modified PHP script.
Please add my codelines in your post too as the php script is waiting in vain for 'subfolder' now..
In general you should add much more echo()'s to your script to see what is really happening. Otherwise you stay blind.
I've tried but still nothing. In output I get error: Notice: Undefined index: filUpload in /var/www/zon/uploadFile.php on line 21. And also subfolder is not created. The content of subfolder variable is correcty defined and in echo output I can see it. Also I have rights for writing inside upload folder so this is not a problem.
|
0

Try this way..it worked for me..

      FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);
               System.out.println(url);
               // 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("image_1", imgs);


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

                 // add parameters
                 dos.writeBytes(twoHyphens + boundary + lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name=\"type\""
                         + lineEnd);
                 dos.writeBytes(lineEnd);

                 // assign value


                 // send image
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name='image_1';filename='"
                         + imgs + "'" + 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);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // 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() {
                        @SuppressWarnings("deprecation")
                        public void run() {


                            try 
                            {


                                DataInputStream dataIn = new DataInputStream(conn.getInputStream());
                                String inputLine;
                                while ((inputLine = dataIn.readLine()) != null) 
                                {
                                    result += inputLine;
                                    System.out.println("Result : " + result);
                                }
                                //result=getJSONUrl(url);  //<< get json string from server
                                //JSONObject jsonObject = new JSONObject(result);
                                JSONObject jobj = new JSONObject(result);
                                sta = jobj.getString("status");
                                msg = jobj.getString("msg");
                                System.out.println(sta + " >>>>>>> " + msg);


                            } 
                            catch (Exception e) 
                            {
                                e.printStackTrace();
                            }


                        }
                    });                
               }    

2 Comments

The code I had posted works perfect but all I want is to change upload folder through code. For example the root folder is upload but I want to also have ability to upload file in subfolder of upload folder.
'conn.setRequestProperty("image_1", imgs);' Can you explain what this statement does? What is the value of 'imgs'. What is the php code to retrieve this info?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.