0

I am sending image to server using HTTPUrlConnection. How to write php code to receive image and send response without json. Could you please explain how php will receive file data without json structure.

 public void uploadFile(String sourceFileUri, String upLoadServerUri) {
    URL url=null;
    HttpURLConnection connection = null;

    Bitmap bm = BitmapFactory.decodeFile(sourceFileUri);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 10, bao);

    try {
            //Create connection
            url = new URL(upLoadServerUri);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());

            writer.writeBytes(bao.toString());
            writer.flush();
            writer.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();


        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
}

1 Answer 1

2

this is my code which is working. //android

String sourceFileUri = Environment.getExternalStorageDirectory()+"filename.jpeg";

            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()) {

                return null;

            }

            String fullpath = "";

            fullpath = sourceFile + "";
            Log.e("fullpath", fullpath);
            try {
                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFileUri);
                Log.e("fileinputstream", "" + fileInputStream);
                URL url = new URL("abc.com/upload.php");
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                        .permitAll().build();
                StrictMode.setThreadPolicy(policy);
                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                // int lenghtOfFile = conn.getContentLength();
                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("bill", fileName);

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

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                        + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();
                Log.e("" + bytesAvailable, "BytesAvailable");
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                Log.e("" + buffer, "Buffer");
                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                // long total = 0;
                Log.e("" + bytesRead, "BytesRead");
                while (bytesRead > 0) {
                    // total += count;
                    // publishProgress("" + (int) ((total * 100) /
                    // lenghtOfFile));

                    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)

           String serverResponseMessage = conn.getResponseMessage();  
                Log.e("Server Response code", "" + serverResponseCode);
                if (serverResponseMessage == "sucess") {


                     System.out.println("file uploaded");
                }

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (Exception e) {
                Log.d("error", e.getMessage());
            }

//php

<?php
    if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
     $name="filename";   

     $tmp_name = $_FILES['bill']['tmp_name'];
     $pic_name = $_FILES['bill']['name'];
     $ext = explode('.',$pic_name);
     $extension = $ext[1];
       if($extension=='png'){
           unlink( $name.'.jpg'); 
            }

      if($extension=='jpg'){
           unlink( $name.'.png'); 
             }

      move_uploaded_file($tmp_name,  $name.'.'.$extension );
            echo "sucess";
            }
        else{
         echo "File not uploaded successfully.";
            }        
     ?>
Sign up to request clarification or add additional context in comments.

2 Comments

thanks raj, The same thing i have seen at many places but can you please explain why we are using String twoHyphens = "--"; String boundary = "*****"; And is it necessary . How to fetch data from PHP code using "Content-Disposition: form-data; name=\"bill\";filename=\"
look down to android code there is serverResponseMessage where you get response from php. which will give you sucess on file upload and file not uploaded on fail.

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.