Upload doc, pdf,xls etc, from android application to php server

20,217

Here is the solution of my question: - Here is code of php file - file.php

<?php

// DISPLAY FILE INFORMATION JUST TO CHECK IF FILE OR IMAGE EXIST
echo '<pre>';
print_r($_FILES);
echo '</pre>';

// DISPLAY POST DATA JUST TO CHECK IF THE STRING DATA EXIST
echo '<pre>';
print_r($_POST);
echo '</pre>';

$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {

    echo "file saved success";


} else{

   echo "failed to save file";
}?>

Put this file in htdoc folder of Xampp inside test named folder (if there is test folder already then ok, otherwise make a folder named "test"). And also create a folder named "images", in which uploaded file was saved.

Create function to select file from gallery

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                1);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

Inside onActivityResult function

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedFileURI = data.getData();
            File file = new File(selectedFileURI.getPath().toString());
            Log.d("", "File : " + file.getName());
            uploadedFileName = file.getName().toString();
            tokens = new StringTokenizer(uploadedFileName, ":");
            first = tokens.nextToken();
            file_1 = tokens.nextToken().trim();
            txt_file_name_1.setText(file_1);
        }
    }

This is asyncTask to upload file to server,

public class PostDataAsyncTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setCancelable(false);
        pDialog.setMessage("Please wait ...");
        showDialog();
    }

    @Override
    protected String doInBackground(String... strings) {
        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("https://10.0.2.2/test/file.php");

            file1 = new File(Environment.getExternalStorageDirectory(),
                    file_1);
            fileBody1 = new FileBody(file1);

            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file1", fileBody1);

            httpPost.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {
                final String responseStr = EntityUtils.toString(resEntity)
                        .trim();
                Log.v(TAG, "Response: " + responseStr);

            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        hideDialog();
        Log.e("", "RESULT : " + result);

    }
}

Call the asyncTask on button click after selecting the file from gallery.

btn_upload.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new PostDataAsyncTask().execute();

        }
    });

Hope this will help you. Happy To Help and Happy Coding.

Share:
20,217
Sanwal Singh
Author by

Sanwal Singh

Mobile Application Developer

Updated on July 06, 2022

Comments

  • Sanwal Singh
    Sanwal Singh almost 2 years

    I get stuck at that place and unable to send doc file to php server. I am using this code.

    Here is PHP code.

    if($_SERVER['REQUEST_METHOD']=='POST'){
    
        $image = $_POST['image'];
                $name = $_POST['name'];
    
        require_once('dbConnect.php');
    
        $sql ="SELECT id FROM volleyupload ORDER BY id ASC";
    
        $res = mysqli_query($con,$sql);
    
        $id = 0;
    
        while($row = mysqli_fetch_array($res)){
                $id = $row['id'];
        }
    
        $path = "uploads/$id.doc";
    
        $actualpath = "http://10.0.2.2/VolleyUpload/$path";
    
        $sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";
    
        if(mysqli_query($con,$sql)){
            file_put_contents($path,base64_decode($image));
            echo "Successfully Uploaded";
        }
    
        mysqli_close($con);
    }else{
        echo "Error";
    }
    

    Here is Java code

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("file/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                PICK_IMAGE_REQUEST);
    }
    

    I called asynTask on upload button.

    if (v == buttonUpload) {
            // uploadImage();
            new PostDataAsyncTask().execute();
        }
    

    A function calls in doInBackground is

    private void postFile() {
        try {
    
            // the file to be posted
             String textFile = Environment.getExternalStorageDirectory()
             + "/Woodenstreet Doc.doc";
             Log.v(TAG, "textFile: " + textFile);
    
            // the URL where the file will be posted
            String postReceiverUrl = "http://10.0.2.2/VolleyUpload/upload.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);
    
            // new HttpClient
            HttpClient httpClient = new DefaultHttpClient();
    
            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);
    
            File file = new File(filePath.toString());
            FileBody fileBody = new FileBody(file);
    
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file", fileBody);
            httpPost.setEntity(reqEntity);
    
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
    
            if (resEntity != null) {
    
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " + responseStr);
    
                // you can add an if statement here and do other actions based
                // on the response
            }
    
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    The exception I get is that

    java.io.FileNotFoundException: content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc: open failed: ENOENT (No such file or directory)
    

    There is file in emulator - test.doc. Is there is any thing I miss in code, please help me. Or suggest a tutorial to upload pdf to php server.

    Thanks In Advance.

    • Sanwal Singh
      Sanwal Singh over 8 years
      Down vote for what, explain please.
    • Professor Abronsius
      Professor Abronsius over 8 years
      which part do you feel is not working - the php or the java?
    • Sanwal Singh
      Sanwal Singh over 8 years
      I don't know where i make mistake, some time file is send to server but it was empty file.
    • Professor Abronsius
      Professor Abronsius over 8 years
      It looks like you are simply creating a file using file_put_contents - there is none of the usuaal php associated with uploading files that I can see
    • Sanwal Singh
      Sanwal Singh over 8 years
      In my code i get select a file which was place in mobile, now i have to sent this file to php server. I did it, file was empty.
    • Professor Abronsius
      Professor Abronsius over 8 years
      There seems to be some ambiguity with your code and question. The PHP is looking for image, the Java code references and suggests an image upload Select Picture or PICK_IMAGE_REQUEST but your question states that there is a file called test.doc but you want to know how to upload a pdf?.... confused!
    • Sanwal Singh
      Sanwal Singh over 8 years
      Okay, Forget everything that write above. I want to do that is, I have to upload a text or a PDF or a doc file to PHP server, now please tell me how i do that. Do you have any reference tutorial or example.
    • Sanwal Singh
      Sanwal Singh over 8 years
      That problem resolve..
  • Arpit Patel
    Arpit Patel almost 8 years
    what is first , file1 ,token, ??
  • Sanwal Singh
    Sanwal Singh almost 8 years
    file1 is File , token is StringTokenizer to split string, First is string in which first string save come after splitting string
  • Arpit Patel
    Arpit Patel almost 8 years
    and use Httpurlconnection because httpclient is depriciated
  • Sanwal Singh
    Sanwal Singh almost 8 years
    Project is not here, it just answer.
  • Tabish khan
    Tabish khan over 5 years
    what if we use volley? Shane
  • Sanwal Singh
    Sanwal Singh over 5 years
    Try to encode image into Base64 string and at server side decode this Base64 string into respectively format.