Upload image using android & php

2019-08-29 17:10发布

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.

2条回答
看我几分像从前
2楼-- · 2019-08-29 17:28

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


                        }
                    });                
               }    
查看更多
萌系小妹纸
3楼-- · 2019-08-29 17:42

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).

查看更多
登录 后发表回答